Monday, January 18, 2010

Displaying Warning Messages in ASP.NET pages- I

Thought of a situation when you need to call javascript alert from your server side code that might include some server side decision logic to handle the alert. Most of us know a straight way- "Page.ClientScript.RegisterStartupScript" method to accomplish this. Althoght accidentally, I came to know another approach to do the same without -   "Page.ClientScript.RegisterStartupScript".

Switch to the HTML view of your Web form and add the following immediately after the close of the <body> tag:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>

</body>
<script>
<asp:Literal id="ltlAlert" runat="server" EnableViewState="False">    </asp:Literal>
 </script>
</html>
Switch back to Design view and save your Web form. This has set up your Literal server control manually—due to the surrounding <script> tags; we couldn't do this using the designer
Add the following code snippet behind your Web form. This takes a string and incorporates it into a JavaScript 'alert' command, which is then placed on the Web page as pure HTML:
private void Say(string Message)
    {
        // Format string properly 
        Message = Message.Replace("'", "\\'");
        Message = Message.Replace(Convert.ToChar(10).ToString(), "\\n");
        Message = Message.Replace(Convert.ToChar(13).ToString(), "");
        // Display as JavaScript alert 
        ltlAlert.Text = "alert('" + Message + "')";
    }
Whenever you want to display an in-your-face message, simply call this Say function in your code—as the following snippet demonstrates:
protected void Page_Load(object sender, EventArgs e)
    {
        Say("this is error msg\n next line");
    }
Thats it!!

No comments:

Post a Comment