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

Aug 10, 2006

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)

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (12) -

 Michal Talaga
Michal Talaga
8/10/2006 7:38:54 PM #

I would improve on this by adding some mechanism of aggregating messages so we could call the Show method multiple times. Then on the client side either display all messages in a single alert or do multiple allerts.
Nevertheless having such a helper class for common JS functions is a very good idea which I'm using on all my projects. Nice stuff!

Mads Kristensen
Mads Kristensen
8/10/2006 7:54:17 PM #

Sure, you could do that very easy by adding a StringCollection property to the Alert class and then add messages by Alert.Message.Add("message"). On the other hand, wouldn't it be better to let the code-behind decide what status message to write back to the client? For instance, you could add a private string variable to the page, and then give it different values depending on the progress made in various methods. Add the end of the Button.Click event handler, just write Alert.Show(_TheStringVariable); You don't want to have JavaScript make those kinds of decisions unless you have some special need to. I can't imaging what those needs would be though...

But the idea of extending the class to individual needs are allways disireable.

 Steve Hebert
Steve Hebert
8/11/2006 7:38:54 PM #

A couple of thougths -

If you use RegisterStartupScript, then the page contents get shown before the popup is displayed.

If you then add an overloaded method for Alert.Show( string message, string url), you can redirect immediately after showing the page.

 Steve Hebert
Steve Hebert
8/11/2006 7:40:17 PM #

I meant - redirect immediately after showing the Alert box.

RyanOC
RyanOC
8/21/2006 11:03:10 AM #

heres what I use...
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


/// Summary description for RDK

namespace RDK
{

    /// A class that handles all c# javasctipt calls.

    public class JAVASCRIPT
    {

        /// displays an alert box with a specified message

        public static void Alert(string message)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"-script language=JavaScript>");
            sb.Append(@"alert('" + message + "');");
            sb.Append(@"</");
            sb.Append(@"script>");

            ((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
        }


        /// Displays an OkConfirm box with a specified message and will redirect to a specified URL if the Ok button is pressed

        public static void OkConfirm(string message, string hyperLink)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"-script language=JavaScript>");
            sb.Append(@"if (confirm('" + message + "')) {location='" + hyperLink + "'};");
            sb.Append(@"</");
            sb.Append(@"script>");

            ((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
        }


        /// Displays a prompt box that will direct the user to a specified hyperlink with a specified querystring definition for an ok click or a cancel click. The querystring value will be inserted by the entered value in the prompt box only if ok was clicked. No need to enter any equal or question mark characters.

        public static void PromptBox(string message, string defaultPromptvalue, string hyperlink, string queryString, string cancelHyperlink)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"-script language=JavaScript>");
            sb.Append(@"var return_value = prompt('" + message + "', '" + defaultPromptvalue + "');");
            sb.Append(@"if (return_value != null)");
            sb.Append(@"{location='" + hyperlink + "?" + queryString + "=' + return_value;}");
            sb.Append(@"else");
            sb.Append(@"{location='" + cancelHyperlink + ";}");
            sb.Append(@"");
            sb.Append(@"</");
            sb.Append(@"script>");

            ((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
        }
    }
}

 Amrit
Amrit
9/6/2006 9:17:09 AM #

Nice one.

 Sumit Kumar Sharma
Sumit Kumar Sharma
10/12/2006 8:22:31 AM #


public static void OkConfirm(string message, string hyperLink)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"-script language=JavaScript>");
sb.Append(@"if (confirm('" + message + "')) {location='" + hyperLink + "'};");
sb.Append(@"</");
sb.Append(@"script>");

((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
}


This is having an mistake So please use this insted of the above one

public static void OkConfirm(string message, string hyperLink)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"script language=JavaScript>");
sb.Append(@"if (confirm('" + message + "')) {location='" + hyperLink + "'};");
sb.Append(@"</");
sb.Append(@"script>");

((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
}

 Satheesh
Satheesh
3/12/2007 10:48:09 AM #

The code helped me a lot...
but one problem wat i am facing is ...
if i click the Submit button... the alert message is displayed in the entire screen... making the submit form itself hidden... How to rectify that?

And one more thing what i wanna ask is...In the alert header the message i am getting is"The http:1314 says is" and then my message..I dont want the header to be like that

Please help me out in this concern

viagra pill
viagra pill Albania
6/23/2008 7:30:29 AM #

<b><a href="rocking-offers.com/tds/go.php?sid=2">Order Viagra for lowest prices!</a><br>
Major website to order Viagra online.<br>
Fast, cheap and discreet delivery.<br>
Order Viagra right now!<br>
<a href="rocking-offers.com/tds/go.php?sid=2">ORDER VIAGRA ONLINE - CLICK HERE!</a></b><br>
<b>How Viagra Works</b><br>This medication works to relax those muscles that limit blood flow to the penile area. This blood flow is vital in gaining and maintaining an erection. Without the relaxation of this muscle and blood flow, you are unable to get an erection.<br><b><a href="rocking-offers.com/.../go.php; ORDER VIAGRA ONLINE - CLICK HERE! ««</a></b><br><br>
<a href="www.blinklist.com/.../a>; Billig-Viagra im Web <a href="www.cccure.org/.../a>; Der Pharmakonzern Pfizer <a href="www.cleveland.com/.../profile.ssf side effects</a> und der Software-Konzern Microsoft haben <a href="www.conceptart.org/.../member.php side effects</a> Potenzpille Viagra im Internet geklagt <a href="forum.dhsoftwares.com/member.php cialis online</a> <a href="community.enemyterritory.com/.../a>; <a href="www.epinions.com/.../show_~View_Profile">viagra uk</a> <a href="www.esnips.com/.../a>; <a href="www.fotolog.com/ed_expert/about">buy soma online</a>  <a href="www.imeem.com/.../cheap_viagra_online">tramadol online</a> <a href="www.gamespot.com/.../show_blog_entry.php for sale</a> <a href="www.ipetitions.com/.../edmeds">discount viagra</a> <a href="www.ittoolbox.com/.../ed_expert">melatonin side effects</a>  <a href="my.mediapost.com/.../a>; <a href="www.mixx.com/users/ED_Expert">hgh</a>; <a href="www.discountorlandovacation.com/.../a>;    <a href="www.discountorlandovacation.com/.../showthread.php viagra</a>    <a href="http://en.netlog.com/ed_expert">; buy soma</a> <a href="www.pctools.com/.../a>; <a href="www.plime.com/.../a>; <a href="www.profileheaven.com/.../a>; <a href="www.netscape.com/.../a>;  <a href="www.simplemachines.org/.../index.php tramadol online</a> <a href="forum.swsoft.com/.../a>; <a href="forums.omnigroup.com/.../a>;  <a href="thepoetryforum.co.uk/.../a>; <a href="http://www.tinyos.net/scoop/user/Dr Viagra">cheap soma</a> <a href="discussion.treocentral.com/member.php side effects</a> <a href="www.tubanews.com/.../member.php side effects</a> <a href="http://profiles.wikidot.com/profile:ed-expert">viagra sale</a> <a href="www.wikio.com/.../a>; <a href="forums.winamp.com/showthread.php viagra</a> <a href="forums.winamp.com/member.php cialis</a> <a href="www.wowzamedia.com/.../member.php xanax online</a> <a href="forum.lycos.de/member.php?u=28754">cheap cialis online</a>

rob
rob United States
7/8/2008 3:38:41 AM #

Question:
When I call Show() from a page OnLoad the box displays correctly. When i call it from a button onClick, the alert box never displays. When I step through the code, it's called, but never shows. Something to do with the post back ?  Maybe the page is getting in the way ?

thanks !

Suidakra
Suidakra Lebanon
7/14/2008 9:59:48 AM #

In the alert header the message i am getting is"The http:1314 says is" and then my message..I dont want the header to be like that

Please help me out in this concern

zero_one
zero_one Egypt
8/19/2008 10:59:41 AM #

i want to make confirm message  not alert only
how can i make class confirm

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.