Javascript Alerts in ASP.NET

4. April 2008

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.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET, Javascript ,

blog comments powered by Disqus