Quantcast

JavaScript: Alert.Show(message) from ASP.NET Code-behind

Get the WebProNews Newsletter:


[ Business]

In highly interactive websites and intranet sites, you probably want to let the users know what’s going on when they delete, save, export etc. on the site.

Those kinds of status messages are widely used and are often implemented by a JavaScript alert box on the web page. ASP.NET doesn’t natively support JavaScript functions from the code-behind files. You manually have to print out a script tag and add the alert() call to it.

As easy as it may be, the extensive use of the alert() status message though out a website calls for a unified and simple implementation in order to avoid duplicate code – a centralized method.

In Windows Forms it is very easy to pop up a status message by calling MessageBox.Show(“message”). It is that kind of object model we want in ASP.NET for printing out JavaScript alerts. We want Alert.Show(“message”) in ASP.NET.

Such a thing doesn’t exist so we have to create it our selves.

I’ve written a static class called Alert with one public method called Show. The implementation is as simple as can be. Just put the .cs file in the App_Code folder on your website and you instantly have access to the method from all pages and user controls.

using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class Alert
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
public static void Show(string message)
{
   // Cleans the message to allow single quotation marks
   string cleanMessage = message.Replace("'", "\\'");
   string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

   // Gets the executing web page
   Page page = HttpContext.Current.CurrentHandler as Page;

   // Checks if the handler is a Page and that the script isn't allready on the Page
   if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
   {
     page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
   }
}
}

Demonstration

That class of only 30 lines of code enables us to add a JavaScript alert to any page at any time. Here is an example of a Button.Click event handler that uses the method for displaying status messages.

void btnSave_Click(object sender, EventArgs e)
{
   try
   {
     SaveSomething();
     Alert.Show("You document has been saved");
   }
   catch (ReadOnlyException)
   {
     Alert.Show("You do not have write permission to this file");
   }
}

If something was saved without problems, this JavaScript alert box will apear to the user of the website:

Download

Alert.zip (0,57 KB)

Comments

Tag:

Add to Del.icio.us | Digg | Reddit | Furl

Bookmark WebProNews:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/

JavaScript: Alert.Show(message) from ASP.NET Code-behind
About Mads Kristensen
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/ WebProNews Writer
Top Rated White Papers and Resources
  • eric matsuno

    Unless I’m missing something, the http context must be inherited and therefore must belong to the page from whence it is being called. so this can’t be part of a separate library. Am I wrong about this?

  • vishnu

    Hi,
    That was great piece of code.
    Thanks a alot. It helped me.

    But a problem is still there.
    After showing alert message, i am navigating to another page from the current page.In that page if i am clicking on Browser’s back button, it shows that previous alert message again. Getting alert message at that point of time is unexpected by user and it wont make sense.

    Is there any work around for this?

  • Rafael

    Thanks. It ‘s what I needed. You helped me a lot!

     

  • Guest

    wow this is incredible!!!

  • Guest

    This code works well as stated in the example above. But if you have a Response.Redirect call right after the alert, the alert popup is never displayed.

  • Guest

    Doesn’t work at all for me (Asp.net (vb))

    although the RegisterScriptBlock is called, nothing is placed on the page and the alert box doesn’t show!

  • azhaguraj

    If i use this coding , alert box shows successfully. But the background form is not visible by user except the alert box. After clicking alert box ok button then only it shows the form.

     

  • John

    Well done. Works fine on my projects. Congratulations to the author.

  • http://ie-mem.com fayjaa

    thank you, work in my project

  • Guest

    It’s working fine for me…….

    Thanks,

  • Satyendra

    see its fine that it is showing the alerts but the problem is that if the alert is active then the content of the page will disappeared, which not make any sense.

  • Guest

    Ver nice code.

  • Guest

    Too Good.. Thankx…

  • satyam

    good article.
    whenever alert msg come window is blanked why?

  • vishal

    Thanks

    it is very helpful and good understable as like a live learning

    thank u very much

  • http://helpdesk kumar chaudhari

    not able to download the code(zip file)

  • Join for Access to Our Exclusive Web Tools
  • Sidebar Top
  • Sidebar Middle
  • Sign Up For The Free Newsletter
  • Sidebar Bottom