Click here to Skip to main content
Click here to Skip to main content

Simple MessageBox functionality in ASP.NET

By , 24 Jun 2004
 

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:

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

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Lee Gunn
Web Developer
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control [modified]memberma tju4 Mar '09 - 19:48 
Dear Vivek,
 
I don't think this is the solution to my application that i want it. But solution to my question is, yes. Wink | ;)
 
If i use server.transfer then there no use for me to use update panel control. I dont want to postback my current form again. Im am still looking for other solution. Any ideas? Anyone? Confused | :confused:
 
Regards,
matju
 
ma tju
Pengaturcara Perisian
Subang Jaya,Selangor, Malaysia
 
Ring Master SB MVP 2008 Poke tongue | ;-P
Subang Jaya MOP (Otai)
modified on Thursday, March 5, 2009 2:58 AM

GeneralRe: Using MessageBox.show in ajax control toolkit tab panel control [modified]memberphuongdai8 Feb '12 - 20:58 
do you have solution ?
GeneralNice, one More QuestionmemberVuyiswa Maseko17 Aug '08 - 10:45 
I was more into Windows Development, the Future of Web is Promising, So i recently started to move to web. You can include the namespace System.Windows.Forms to use the Messagebox that was nicely used in Windows development. I understand why you dont use it in your ASP.net. Do you think its a bad idea to use it? please explain. gave you 5 Smile | :)
 
Thanks
 
Vuyiswa Maseko,
 
Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding
 
VB.NET/SQL7/2000/2005
http://vuyiswamb.007ihost.com
http://Ecadre.007ihost.com
vuyiswam@tshwane.gov.za
 

GeneralRe: Nice, one More Questionmembervivek kumar gupta 200825 Oct '08 - 23:00 
We cannot use System.Windows.Forms.MessageBox in web application. If you try to use it then it misbehaves, it appears in the task bar, not on the parent browser. Then you have to click on task bar to show it over web form.
GeneralRe: Nice, one More QuestionmemberVuyiswa Maseko26 Oct '08 - 5:45 
Thanks that is true, i see it misbehaves. I have started to enjoy
 

Response.write("<script> alert('hello world');</script>");
 
Thanks
 
Vuyiswa Maseko,
 
Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding
 
VB.NET/SQL7/2000/2005
http://vuyiswamb.007ihost.com
http://Ecadre.007ihost.com
vuyiswam@tshwane.gov.za
 

GeneralHany sheblmembershehabstar4 Feb '08 - 9:51 
more Thanks
 
hello

GeneralTell me what Namespace(s) You're UsingmemberBrian Hart16 Oct '07 - 6:57 
I am a .NET newbie. First, I want to thank you for this great article. It's very informative.
 
It would greatly support me in copying your code into my project to use it if you could add a line to the top of the listing for the MessageBox class:
using System.Collections; 

 
Sincerely Yours,
Brian Hart
Department of Physics and Astronomy
University of California, Irvine

GeneralNot working with Ajax.memberThirumalai M24 Mar '07 - 22:22 
Hi Lee ,
 
I have one page using Ajax. I am calling MessageBox.Show("Show a Message"); But it shows error like
Sys.WebForms.PageRequestManagerParserErrorException: This message received from the server could not be parsed. Common causes for this error when the response is modified by calls to Response.Write(), reponse filters, HttpModules, or server trace is enabled.
Details: Error parsed near 'ntryDate"));
});
|<script language='ja'.
 
Thirumalai M
GeneralBrowser back button issuemembertar5657 Sep '06 - 7:19 
Anyone find a solution to the browser back button issue for this class.
GeneralRe: Browser back button issuememberBrian Hart16 Oct '07 - 7:00 
tar565 wrote:
Anyone find a solution to the browser back button issue for this class.

 
Just what are you referring to?
GeneralRe: Browser back button issuememberMember 195309527 Dec '09 - 21:37 
When you navigate away from a page after displaying a MessageBox and then press your browsers Back button, the MessageBox is displayed again.
GeneralMessageBox.Show("Thanks a million!");memberADiMauro25 May '06 - 10:24 
Lee, just wanted to thank you for the awesome code. It is working great in my web app. Lucky for me the Code Project gets searched with the VS2005 Help.
GeneralThanks!!! great, heres the VB.NET version.memberthomasholme16 Feb '06 - 2:50 
I have tested it with ASP.NET 2.0
->
Imports Microsoft.VisualBasic
 
Public Class MessageBox
      Private Shared m_executingPages As New Hashtable()
 

      Private Sub New()
      End Sub 'New
 
      Public Shared Sub Show(ByVal sMessage As String)
            ' If this is the first time a page has called this method then
            If Not m_executingPages.Contains(HttpContext.Current.Handler) Then
                  ' Attempt to cast HttpHandler as a Page.
                  Dim executingPage As Page = HttpContext.Current.Handler '
                  'ToDo: Error processing original source shown below
                  '
                  '
                  '--------------------------------------------------------^--- Syntax error: ';' expected
 
                  If Not (executingPage Is Nothing) Then
                        ' Create a Queue to hold one or more messages.
                        Dim messageQueue As 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.
                        AddHandler executingPage.Unload, AddressOf ExecutingPage_Unload
                  End If
            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.
                  Dim queue As Queue = CType(m_executingPages(HttpContext.Current.Handler), Queue)
 
                  ' Add our message to the Queue
                  queue.Enqueue(sMessage)
            End If
      End Sub 'Show
 
      ' Our page has finished rendering so lets output the
      ' JavaScript to produce the alert's
      Private Shared Sub ExecutingPage_Unload(ByVal sender As Object, ByVal e As EventArgs)
            ' Get our message queue from the hashtable
            Dim queue As Queue = CType(m_executingPages(HttpContext.Current.Handler), Queue)
 
            If Not (queue Is Nothing) Then
                  Dim sb As New StringBuilder()
 
                  ' How many messages have been registered?
                  Dim iMsgCount As Integer = queue.Count
 
                  ' Use StringBuilder to build up our client slide JavaScript.
                  sb.Append("<script language='javascript'>")
 
                  ' Loop round registered messages
                  Dim sMsg As String
                  While (iMsgCount > 0)
                        iMsgCount = iMsgCount - 1
                        sMsg = CStr(queue.Dequeue())
                        sMsg = sMsg.Replace(ControlChars.Lf, "\n")
                        sMsg = sMsg.Replace("""", "'")
                        sb.Append("alert( """ + sMsg + """ );")
                  End While
                  ' 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())
            End If
      End Sub 'ExecutingPage_Unload
 
End Class 'MessageBox
 


AnswerRe: Thanks!!! great, heres the VB.NET version.membertimo1875 Aug '07 - 23:05 
or even better to use in stead of
 
sMsg = sMsg.Replace(ControlChars.Lf, "\n")
 
is
 
sMsg = sMsg.Replace(Environment.NewLine, "\n")

 
tmo
GeneralRe: Thanks!!! great, heres the VB.NET version.memberchris_wanaka1 Nov '07 - 15:33 
Thanks a lot for translating that and taking the time to share your code. Just what I was after Smile | :)
QuestionHow About a Yes No Message Boxmemberudaan29 Nov '05 - 12:23 
Could you give me a start on Yes No Message Box on ASP.Net.
 
Thanks
Generaluse globallymemberrooker000728 Aug '05 - 19:29 
how do you use one MessageBox() class to accomodate other forms? is it possible?
GeneralRe: use globallymemberLee Gunn30 Nov '05 - 6:18 
Hi,
 
I wrote this a while back, but from what i can see you should be able to use it globally as it uses a static hashtable to store all of the Message Queues by using the current IHttpHandler as the key (most likely a Page Class)
 
Freelance Software Developer - Glasgow
http://www.secretorange.co.uk
GeneralOne note....membertemp891089 May '05 - 13:03 
I don't know if this caused anyone else a hiccup, but I needed to add the following statements so it worked...
 
using System;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
 
Hopefully it'll save someone a few moments of researching through the class brower. Wink | ;-)
Generalhelpmemberleohuang25 Jan '05 - 2:40 
Confused | :confused: Can you use VBScript MsgBox method to show a message box,and in server side can get which button clicked.like OK or Cancel etc.
GeneralOne small change.memberGnemesis24 Nov '04 - 8:16 

In this section:
 
         while( iMsgCount-- > 0 )
         {
            sMsg = (string) queue.Dequeue();
            sMsg = sMsg.Replace( "\n", "\\n" );
            sMsg = sMsg.Replace( "\"", "'" );
            sb.Append( @"alert( """ + sMsg + @""" );" );
         }
 
I added the following:
sMsg = sMsg.Replace( "\r", "\\r" );
 
I have been using this control to send alerts when a user enters an invalid Regex string. Often the error.Message text contains embedded \r's, which will make MessageBox crash with an unterminated string exception.
 
Other than that, it has been working very well for me.
 
=jeff

Generalscript outside of htmlsussanonymous17 Nov '04 - 13:33 
The only problem I can see is that because it's adding the script using Response.Write on page unload, the page has already been completely rendered, and so the output is going after the closing </html>... it still works in at least IE 6 and Firefox 1, but I'm not sure it's good practice to write anything outside of that.. or if it will remain compatible in future browser versions.
GeneralRe: script outside of htmlmemberLee Gunn30 Nov '05 - 6:22 
Yeah, I didnt like doing that much either...but the purpose of that was to ensure that the JavaScript executed after the page had fully rendered on screen. I suppose it should really hook into the body.onLoad event but it seemed a bit of a hassel getting it to work cross browser
 
Freelance Software Developer - Glasgow
http://www.secretorange.co.uk
Generalanother waymemberTodd.Harvey18 Oct '04 - 11:09 
Lee's approach has some advantages - here's another way to send a message from server to browser:

// ********************************************
// purpose - send an alert message to the client
private void Send_ClientAlert(string strMessage)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(5);
sb.Append("<script language=\"JavaScript\">");
sb.Append("alert('");
sb.Append( strMessage );
sb.Append("');");
sb.Append("</script>");
RegisterClientScriptBlock("showSaveMessage", sb.ToString() );
}
 
vb
' ********************************************
' purpose - send an alert message to the client
' called by - Page_Load
Private Sub Send_ClientAlert(ByVal strMessage As String)
' init the string builder for at least 5 items
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder(5)
' create the javascript command to send an alert to the user (it will be inserted
' at the top of the web page, in the head section, I believe (note - you can't just response.write this stuff - it will be at the very top of html)
sb.Append("<script language=""JavaScript"">")
sb.Append("alert('")
sb.Append(strMessage)
sb.Append("');")
sb.Append("</script>")
RegisterClientScriptBlock("showSaveMessage", sb.ToString())
End Sub
 

GeneralRe: another waymemberMolkin11 Apr '05 - 6:32 
Great !!!

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 25 Jun 2004
Article Copyright 2004 by Lee Gunn
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid