Click here to Skip to main content
15,868,016 members
Articles / Web Development / HTML

Simple MessageBox functionality in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.65/5 (60 votes)
30 Nov 2016CPOL2 min read 576.9K   10.4K   135   49
An article describing how to offer simple MessageBox functionality in ASP.NET
Ask me questions on twitter: @leegunn.

Introduction

When moving from Windows Forms to ASP.NET Web Forms, an API that may be missed is that offered by the System.Windows.Forms.MessageBox Class. Sometimes when developing web forms the application may wish to inform the user of a successful or, god forbid, an unsuccessful operation. An effective way to communicate an important message to the user is through the use a MessageBox or, with respect to web programming, a JavaScript "alert".

The MessageBox class in the System.Windows.Forms namespace is usable only from Windows Forms and NOT ASP.NET Web Forms. In order to alert the user we need to inject some client side code into the HTML page. This is a simple task but can become quite a nuisance if this functionality is required on a regular basis.

I thought that it would be nice if we could simply call a static method from any page that would deal with the client side JavaScript required to display the alert's. I decided to write a small MessageBox class with a static Show(); method.

Using the code

To use this code in your projects, simply call the static Show() method of the MessageBox class and pass in the string that you wish to display to the user.

For example:

C#
private void Page_Load( object sender, System.EventArgs e )
{
  MessageBox.Show( "Hello World!" );
  MessageBox.Show( "This is my second message." );
  MessageBox.Show( "Alerts couldnt be simpler." );
}

As you can see from the example above, the developer isn't restricted to displaying one message box.

Behind the scenes

The first time the Show method is invoked from a Page, a System.Collections.Queue is created and stored in a private static HashTable. The Queue is used to hold all of the message's associated with current executing Page. We also "wire up" the Page.UnLoad event so we can write the client side JavaScript to the response stream after the Page has finished rendering its HTML.

The reason we store the Queue in a Hashtable is because we are using static methods. There is the potential for multiple pages to be using the class at the same time (on separate threads). Therefore we need to make sure we know which messages belong to which page. To accomplish this we simply use the Page's reference as the key in the HashTable. We obtain a reference to the current executing page by casting the current IHttpHandler to System.Web.UI.Page. The current IHttpHandler can be obtained from HttpContext.Current.Handler. In most cases this will be a class either directly or indirectly derived from System.Web.UI.Page.

Source Code

C#
public class MessageBox
{
  private static Hashtable m_executingPages = new Hashtable();

  private MessageBox(){}

  public static void Show( string sMessage )
  {
    // If this is the first time a page has called this method then
    if( !m_executingPages.Contains( HttpContext.Current.Handler ) )
    {
      // Attempt to cast HttpHandler as a Page.
      Page executingPage = HttpContext.Current.Handler as Page;

      if( executingPage != null )
      {
        // Create a Queue to hold one or more messages.
        Queue messageQueue = new Queue();

        // Add our message to the Queue
        messageQueue.Enqueue( sMessage );

        // Add our message queue to the hash table. Use our page reference
        // (IHttpHandler) as the key.
        m_executingPages.Add( HttpContext.Current.Handler, messageQueue );

        // Wire up Unload event so that we can inject 
        // some JavaScript for the alerts.
        executingPage.Unload += new EventHandler( ExecutingPage_Unload );
      }   
    }
    else
    {
      // If were here then the method has allready been 
      // called from the executing Page.
      // We have allready created a message queue and stored a
      // reference to it in our hastable. 
      Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];

      // Add our message to the Queue
      queue.Enqueue( sMessage );
    }
  }


  // Our page has finished rendering so lets output the
  // JavaScript to produce the alert's
  private static void ExecutingPage_Unload(object sender, EventArgs e)
  {
    // Get our message queue from the hashtable
    Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];

    if( queue != null )
    {
      StringBuilder sb = new StringBuilder();

      // How many messages have been registered?
      int iMsgCount = queue.Count;

      // Use StringBuilder to build up our client slide JavaScript.
      sb.Append( "<script language='javascript'>" );

      // Loop round registered messages
      string sMsg;
      while( iMsgCount-- > 0 )
      {
        sMsg = (string) queue.Dequeue();
        sMsg = sMsg.Replace( "\n", "\\n" );
        sMsg = sMsg.Replace( "\"", "'" );
        sb.Append( @"alert( """ + sMsg + @""" );" );
      }

      // Close our JS
      sb.Append( @"</script>" );

      // Were done, so remove our page reference from the hashtable
      m_executingPages.Remove( HttpContext.Current.Handler );

      // Write the JavaScript to the end of the response stream.
      HttpContext.Current.Response.Write( sb.ToString() );
    }
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseMany Thanks Pin
Peter J F22-Jul-22 0:15
Peter J F22-Jul-22 0:15 
GeneralThank you Pin
Member 1508543427-Feb-21 0:25
Member 1508543427-Feb-21 0:25 
QuestionGood Pin
Vittorio Morellini2-Dec-16 2:56
Vittorio Morellini2-Dec-16 2:56 
QuestionVote 5 Pin
AshtonAsh30-Nov-16 23:51
AshtonAsh30-Nov-16 23:51 
QuestionWhat is the license? Pin
oyvind515119-Aug-15 22:37
oyvind515119-Aug-15 22:37 
GeneralMy vote of 3 Pin
Member 1000387814-Nov-13 22:29
Member 1000387814-Nov-13 22:29 
QuestionGood Pin
revolutionary.king10-Jun-13 20:31
revolutionary.king10-Jun-13 20:31 
AnswerRe: Good Pin
rupswap31-Oct-14 0:35
rupswap31-Oct-14 0:35 
Bugnot working with updatepanel Pin
er. Mahesh Nagar4-Mar-13 18:52
er. Mahesh Nagar4-Mar-13 18:52 
GeneralRe: not working with updatepanel Pin
Hornwood5092-Dec-16 0:09
Hornwood5092-Dec-16 0:09 
GeneralMy vote of 5 Pin
octaviocruz997-Sep-12 6:59
octaviocruz997-Sep-12 6:59 
QuestionThanks for Great article Pin
Member 381279312-May-12 11:14
Member 381279312-May-12 11:14 
GeneralThis does not work with the update panel with AJAX Pin
Kimmie80002-Nov-10 7:51
Kimmie80002-Nov-10 7:51 
Generalam finding some difficulties in using the code Pin
ankitjain111026-Aug-09 22:52
ankitjain111026-Aug-09 22:52 
QuestionConfirmation MessageBox Version of this code ? Pin
codddy20-Nov-08 0:59
codddy20-Nov-08 0:59 
GeneralUsing MessageBox.show in ajax control toolkit tab panel control Pin
vivek kumar gupta 200825-Oct-08 23:58
vivek kumar gupta 200825-Oct-08 23:58 
GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control Pin
Ma tju4-Mar-09 16:28
Ma tju4-Mar-09 16:28 
GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control Pin
vivek kumar gupta 20084-Mar-09 17:21
vivek kumar gupta 20084-Mar-09 17:21 
GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control [modified] Pin
Ma tju4-Mar-09 19:48
Ma tju4-Mar-09 19:48 
GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control [modified] Pin
phuongdai8-Feb-12 20:58
phuongdai8-Feb-12 20:58 
GeneralNice, one More Question Pin
Vimalsoft(Pty) Ltd17-Aug-08 10:45
professionalVimalsoft(Pty) Ltd17-Aug-08 10:45 
GeneralRe: Nice, one More Question Pin
vivek kumar gupta 200825-Oct-08 23:00
vivek kumar gupta 200825-Oct-08 23:00 
GeneralRe: Nice, one More Question Pin
Vimalsoft(Pty) Ltd26-Oct-08 5:45
professionalVimalsoft(Pty) Ltd26-Oct-08 5:45 
GeneralHany shebl Pin
Hany Shebl4-Feb-08 9:51
Hany Shebl4-Feb-08 9:51 
GeneralTell me what Namespace(s) You're Using Pin
Brian C Hart16-Oct-07 6:57
professionalBrian C Hart16-Oct-07 6:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.