Javascript Alerts in ASP.NET

April 4, 2008 14:12 by John M

I know this may not be the newest thing with ASP.NET.  But I get asked how to show javascript alerts in ASP.NET during a postback or some event handler.  I usually just make a class called common.cs and add these functions in them:

public static string SuccessMessage()
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script lang='javascript'>");
        strBldr.Append("alert('Successfully processed your request!");
        strBldr.Append("');");
        strBldr.Append("</script>");
       
        strScript = strBldr.ToString();

        return strScript;
    }

    public static string SuccessMessage(string Message)
    {
        string strScript = null;
        StringBuilder strBldr = new StringBuilder();

        strBldr.Append("<script type=\"text/javascript\">");
        strBldr.Append("alert('Sucessfully processed your request!");
        strBldr.Append(Message);
        strBldr.Append("');");
        strBldr.Append("</script>");

        strScript = strBldr.ToString();
        return strScript;
    }

Then to add the script to the page (say during a button_onclick event) I use the following code:

  this.Page.Controls.Add(new LiteralControl(common.SuccessMessage()));

I know you can use the RegisterStartupScript and RegisterClientScriptBlock, but I prefer to do this when showing alerts.


Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,
Categories: ASP.NET
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

November 21. 2008 05:36

Gravatar