Feb 26, 2008

How To: Create a Message Box Class in C# for Asp .Net

Coming from a windows programming background to the web has it's pros and cons. One of the major annoyances for me was that I was so used to calling MessageBox.Show() every time I needed to inform the user of something.

While I was programming the logic behind the login form I wanted to use MessageBox.Show so I decided to create a class that would render the MessageBox as a Javascript alert. Javascript isn't as extendable as in windows forms so this implimentation is just a simple MessageBox.Show(String value); There are no overloads for changing the caption or the style of the buttons because Javascript will not allow it.

As of right now this class only uses the Javascript alert function. I may extend this to include the confirm and/or prompt functions later on if the need or want arises, but as of right now this will suffice.

Here is the Code for the MessageBox Class:


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

public static class MessageBox
{
// Create a string builder to help format the javascript
private static StringBuilder sb;

public static void Show(string strMessage)
{
// make sure our string builder is initialized with an empty value
sb = new StringBuilder();

// Rewrite our Message to conform with javascript syntax
strMessage = strMessage.Replace("\n", "\\n");
strMessage = strMessage.Replace("\"", "'");

// Create the javascript to be sent to the client
sb.Append("<script language=\"javascript\" type=\"text/javascript\">");
sb.Append(@"alert( """ + strMessage + @""" );");
sb.Append(@"</script>");

// Get the page that is requesting this method
Page pgExecutingPage = HttpContext.Current.Handler as Page;

// Wire up the unload event of the requesting page so that we can
// add our javascript to the end of the response
pgExecutingPage.Unload += new EventHandler(pgExecutingPage_Unload);
}

private static void pgExecutingPage_Unload(object sender, EventArgs e)
{
// Write the javascript to the end of the current response
HttpContext.Current.Response.Write(sb);
}
}

As you can see in the following example MessageBox is set as a Public Static Class. This is so that, just like the windows forms version, we can call its' methods from anywhere in the application without having to create a new instance of the object.

public static class MessageBox {}

Next, we need to create a System.Text.StringBuilder as a private static member of our private static MessageBox Class. We will use the System.Text.StringBuilder to format the javascript that is to be sent to the clients browser.

private static StringBuilder sb;


Then, we create our Show() method as a public static method in MessageBox. Our Show() method takes only one parameter which is a String value containing the message that will be formatted and then shown to the requesting client as a javascript alert.

public static void Show(string strMessage) {}

The first statement in our Show() method initializes our System.Text.StringBuilder and makes sure that the value held in the variable has been emptied each time this method is called. If the StringBuilder is not emptied each time our Show() method is called the new alert will be appended to the string and the clients browser will see a duplicate alert for each time our Show() method was previously called.

sb = new StringBuilder();

The next statements of our Show() method are used to convert the C# way of building strings over to the javascript way of doing the same. The first makes sure that the escape \n is passed instead of a raw line break. The latter converts a double quote into a single quote.


strMessage = strMessage.Replace("\n", "\\n");
strMessage = strMessage.Replace("\"", "'");


Now we construct our Javascript alert function and append it to our System.Text.StringBuilder, our strMessage variable is concatenated between quotes to make: alert("Value of strMessage");


sb.Append("<script language=\"javascript\" type=\"text/javascript\">");
sb.Append(@"alert( """ + strMessage + @""" );");
sb.Append(@"</script>");


In order to append our javascript alert to the requesting page, we'll need a reference to that page. So, let's cast the current requests HttpHandler as a System.Web.UI.Page.


Page pgExecutingPage = HttpContext.Current.Handler as Page


Let's wire up our pgExecutingPage_Unload() method to handle the Unload event of the currently executing page. You could just as easily use the Load event but the MessageBox will render itself before anything else on the page has had a chance to load. In the Unload event it will render itself after everything else on the page has loaded.

pgExecutingPage.Unload += new EventHandler(pgExecutingPage_Unload);

The last method we'll create is the pgExecutingPage_Unload() method. Since we are at the Unload step in the pages execution whatever we add to the response will be appended to the very end of the page.

private static void pgExecutingPage_Unload(object sender, EventArgs e) {}

Finally we just print our System.Text.StringBuilder to the end of the current response stream.

HttpContext.Current.Response.Write(sb);

Well, that's how I put together my MessageBox class. If you found this how to helpful, Please, add a link to it from your site, add it to your social bookmarks or email it to somebody.

0 comments:




Browse Posts by Category