ASP.NET Create Javascript Alert on Server Side

Many times in ASP.net you find yourself needing to create an alert on the client side but you're processing on the server side. The trick is to register a Javascript to the client from the server. I have found a nifty way of creating a class that will allow you to do this.

public static class ClientMessageBox
{

    public static void Show(string message, Control owner)
    {
        Page page = (owner as Page) ?? owner.Page;

        if (page == null)
        {
          return;
        }

        page.ClientScript.RegisterStartupScript(owner.GetType(),
            "ShowMessage", string.Format("<script type="text/javascript">;alert('{0}')</script>",
            message));

    }

}

// Example of using class and method
protected void Page_Load(object sender, EventArgs e)
{
    ClientMessageBox.Show("Hello World", this);
}

You can now call ClientMessageBox.Show('text', this ); anywhere server side and get a nice javascript alert. Now of course there are AJAX control toolkits and other things that do this for you but this is a bare bones pure C# solution.

Comments

Popular Posts