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 staticShow(); 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.

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.

And then, I used this MessageBox class in my application and it works fine. But I also need the Confirmation Message Box, for this reason I changed the code a little. I made some changes in "ExecutingPage_Unload" method. Since I want toget the answer of the user from the C# code, I added "true" for Ok, and "false" for Cancel to web page's Url. This way I will check if it is true or false and decide which button the user has clicked. And it works fine, but the problem is, since the JavaScript code is executed last and the ConfirmationMessageBox is clicked after everything in the ".cs file" is executed, I can not get the true/ false values from the URL.

I just want, the ConfirmationMessageBox to be shown, and get the true/false values from the URL exactly when reaching the "ConfirmationMessageBox.Show()" statement in the .cs file, and then continue with the rest of the code, but it executes "ExecutingPage_Unload" not when I need, but at the end.

HiI am trying to use MessageBox.show on click of a button which is inside update panel but I am not getting the alert message while I am trigger - postback on click of that button(I have tried async postback also i.e. not working also). I want to know, will it work inside update panel or not. Please guide me if I am wrong. Kindly help, Very Urgent.Thanks Vivek

I too faced the same problem but I got its solution. If you have to display the alert message inside update panel then after writing messagebox.show("My Message"), you should use server.transfer(samepage.aspx); This message is displayed at page unload event of current page from browser. Try thislike it

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

Thanks

Vuyiswa Maseko,

Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding

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.

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'.

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()

' 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

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)

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.

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.

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

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
privatevoid 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