Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

ASP.NET C# MessageBox

4.46/5 (21 votes)
23 Jul 2013GPL38 min read 1   5.6K  
This article explains how to create a messagebox class to use in web applications.

img1.png

Website with MessageBox interface

Introduction

In my last two articles titled "Creating a Custom Message Box", I described how to create a simple message box which could be used in desktop applications. In this article, I will explain how to create a message box class in C# to use in web applications.

Background

Any web developer will tell you, if you want to display a message box to a user of a web application, you need to use the JavaScript alert() or confirm() function and these functions are great for displaying simple messages and getting responses. But they lack in many areas such as not being able to add different icons or buttons, and visually they are not great to look at.

Solution

If you want a message box that looks good and to which you can add your own buttons as well as your own icons, then your only solution is to do it yourself. But don't panic, it is really not that difficult. By using a combination of JavaScript and CSS, you can create a message box which your users can respond to.

Solution Explained

Page Dimmer

The first thing that you will need to do is make the page content inaccessible, by this I mean once your message box is displayed, your user will not be able to click on any navigations link on your page without acknowledging the message box. This is where the page dimmer comes in. The page dimmer is simply a div element with a fixed position. What this does is place a div element over your page content. If you were to set the background color of the div, then your page content will no longer be visible.

After placing the div on the page with a fixed position and assuming you have set a background color for the div, your page content will no longer be viewable because the page is placed behind the div as mentioned.

Rather than making the page go white or whatever color when the message box is shown, it would be nice if the background was semi transparent so that you can at least see the page content. If you are not quite sure about what I mean by this, take a look at the screenshot above. Notice that the background is semi-transparent and the page content is still viewable. This gives the impression that the page is dimmed. Thus the name Page Dimmer. Listing 1.1 below is a sample CSS code which demonstrates how to make a div semi-transparent with a fixed position. Note that the background of the page is set to black, with a transparency of 50, which is set as the opacity. If you test the code below, you will not get a sense that the div is partially transparent. It will just appear as though the page is grey. But bear with me, you will get the full effect when you get to turn the page dimmer on and off.

CSS
.page_dimmer 
{ 
position:fixed; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
background-color:#000000; 
filter:alpha(opacity=50); 
-moz-opacity:.50; 
opacity:.50; 
z-index:50; 
}
Listing 1.1

Message Box

After creating a page dimmer, it's time to create the actual message box. The message box will consist of the title, message, and OK button. The inner message box structure needs to be placed in a div. So you can design the layout of the message box however you like. Once you have designed and coded the inner message box structure such as where the title, message and OK button will appear, you need to place the code inside a div. This div needs to be centered on the screen and also fixed. It needs to be fixed so that if your page has scrollbars and the user scrolls down, then the message box should still appear in the same place, but the rest of the page content displayed behind the page dimmer div should scroll up or down.

To position the div in the center of the screen, I used the CSS top, left, and right properties with a percentage, this is not really centering the div, it just gives the illusion that the div is centered horizontally. The code for the message box CSS is listed below in Listing 1.2.

CSS
.msg_box_container 
{ 
position:fixed; 
background-color:#888888; 
border:1px solid #999999; 
z-index:50; 
left:20%; 
right:20%; 
top:20%; 
}
Listing 1.2

Putting It All Together

At this point, I should mention that the message box div should not be nested within the page dimmer div. The reason for this is because the page dimmer is semi transparent and anything placed inside the page dimmer div will also appear transparent. Listing 1.3 below shows the complete CSS and HTML for the message box.

CSS
<style> 
.page_dimmer 
{ 
position:fixed; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
background-color:#000000; 
filter:alpha(opacity=50); 
-moz-opacity:.50; 
opacity:.50; 
z-index:50; 
} 

.msg_box_container 
{ 
position:fixed; 
background-color:#888888; 
border:1px solid #999999; 
z-index:50; 
left:20%; 
right:20%; 
top:20%;" 
} 

</style> 

<div class="page_dimmer" id="pagedimmer"> </div> 
<div class="msg_box_container" id="msgbox"> 
<table width="100%"> 
<tr> 
<td colspan="2">[TITLE]</td> 
</tr> 
<tr> 
<td>[ICON]</td> 
<td>[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2"><input type="Button" value="OK"></td> 
</tr> 
</table> 
</div> 
Listing 1.3

Save the above code and place some content just under the message box div.

The Code

It is now time to take a look at the scripting behind the OK button, which will be used to close the message box and remove the page dimmer. Before I present the JavaScript code, take a look at the code in listing 1.3 again. Take note that both the page dimmer and the message box div have an ID attribute. This is very important, as we will be using JavaScript DOM to get the div reference so that we can turn the visibility of the page dimmer and the message box div on and off. Listing 1.4 below shows how to get a reference to the page dimmer and message box divs (the objects) by using the DOM getElementById() method.

JavaScript
document.getElementById('page_dimmer') 
document.getElementById('msgbox') 
Listing 1.4

The above code is fairly simple and doesn't actually do anything. The code below in listing 1.5 however shows how to set the visibility of each div to hidden.

JavaScript
document.getElementById('pagedimmer').style.visibility = 'hidden' 
document.getElementById('msgbox').style.visibility = 'hidden' 
Listing 1.5

Now that we have the code to set both divs to be hidden, it's time to put all the code together, that is CSS, HTML, and JavaScript. Listing 1.6 below is the complete code for the message box. You can save it and test the OK button.

HTML
<style> 
.page_dimmer 
{ 
position:fixed; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
background-color:#000000; 
filter:alpha(opacity=50); 
-moz-opacity:.50; 
opacity:.50; 
z-index:50; 
} 

.msg_box_container 
{ 
position:fixed; 
background-color:#888888; 
border:1px solid #999999; 
z-index:50; 
left:20%; 
right:20%; 
top:20%;" 
} 

</style> 

<div class="page_dimmer" id="pagedimmer"> </div> 
<div class="msg_box_container" id="msgbox"> 
<table width="100%"> 
<tr> 
<td colspan="2">[TITLE]</td> 
</tr> 
<tr> 
<td>[ICON]</td> 
<td>[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2"><input type="Button" value="OK" 
   onClick="document.getElementById('pagedimmer').style.visibility = 'hidden'; 
          document.getElementById('msgbox').style.visibility = 'hidden'"></td> 
</tr> 
</table> 
</div> 
Listing 1.6

Notice the OnClick event in the input tag?

ASP.NET C# Custom Message Box

It is now time to develop a reusable message box class. Now that we know how to set up a message box, we can easily begin to develop a custom C# class to do away with all the hassle of having to write the code every time we want to use it. At this point, many of you might have some ideas of how to develop the class yourself. But rather than shooting off to write the code, stick around and read a little more.

The approach I have taken to develop the message box class is quite simple. The class consists of six public methods, one of which returns a string. They are as follows:

C#
public void SetTitle(string msg_title) 
public void SetIcon(string msg_icon) 
public void SetMessage(string msg_message) 
public void SetOKButton(string msg_button_class) 
public void AddButton(string msg_button) 
public string ReturnObject() 

The SetTitle() method simply sets the title of the message box. The SetIcon() method sets the icon to be used for the message box. It takes a string as an argument which is the file path of the image to be used as an icon. The SetMessage() method sets the message body of the message box. The SedivtOKButton() actually should not be a method but rather coded in as part of the message box, this is because every message box needs a button to close it. However, in order to show the OK button on the attached sample, you need to call this method. You can remove it and code the OK button in directly. This method takes one argument, which is the CSS class to apply styling to the button. Next is the AddButton() method. This method is responsible for adding additional buttons to the message box, which when clicked will navigate to other pages.

Before you can call the AddButton() method, you need to first create an instance of a MessageBoxButton class. This class simply returns an HTML button code. You set the onClick event of the button, which is basically navigating to another page by using the SetLocation() method of the MessageBoxButton class. You then return the HTML code using the ReturnObject() method and set it as the argument for the AddButton() method. You can create as many instances of the MessageBoxButton class to keep adding buttons to the message box. All you need to do is keep using the AddButton() method, which stores all the HTML code for each button in an ArrayList. Finally, the ReturnObject() method for the MessageBox class returns the HTML code for the message box, including the page dimmer. All CSS is inline.

Templating

Finally, rather than hard coding the structure of the message box code into the MessageBox class, I decided to create a template file, which consists of the page dimmer and message box HTML code along with inline CSS. The template file contains markers which are used to insert the title, icon, message body, and buttons. This approach of using a template allows you to design your own message box layout, giving it the appearance you want. All you have to do is make sure the markers are in the template.

The constructor of the MessageBox class takes one argument, which is the file path of the message box template. Listing 1.7 below shows the contents of the template file.

HTML
<div style="position:fixed;height:100%;width:100%;top:0px;left:0px;
    background-color:#000000;filter:alpha(opacity=55);
    -moz-opacity:.55;opacity:.55;z-index:50;" 
    id="pagedimmer"> </div> 
<div style="position:fixed;background-color:#888888; 
    border:1px solid #999999; z-index:50; left:20%; 
    right:20%; top:20%;" id="msgbox"> 
<div style="margin:5px;"> 
<table width="100%" style="background-color:#FFFFFF; border:1px solid #999999;"> 
<tr> 
<td colspan="2" style="font-family:tahoma; font-size:11px; font-weight:bold; 
    padding-left:5px; background-image: url(msg_title_1.jpg); 
    color:#FFFFFF; height:22px;">[TITLE]</td> 
</tr> 
<tr> 
<td style="width:100px; text-align:center;">[ICON]</td> 
<td style="font-family:tahoma; font-size:11px;padding-left:5px;">[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2" style="border-top:1px solid #CCCCCC; padding-top:5px;
    text-align:right;">[BUTTONS]</td> 
</tr> 
</table> 
</div> 
</div> 
Listing 1.7

The markers are highlighted in bold. Notice also the CSS for both the page dimmer and message box divs are contained in style tags.

Finally, Listing 1.8 and Listing 1.9 below are the code for the MessageBox and MessageBoxButton classes.

C#
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;

public class MessageBox

{
    private string strLine;
    private StringBuilder msgbox;
    private StreamReader readtemplte;
    private string msgbox_title = "";
    private string msgbox_icon = "";
    private string msgbox_message = "";
    private string msgbox_ok_button = "";
    private string msgbox_buttons = "";
    private ArrayList msgbox_button;

    public MessageBox(string tpl_path)
    {
        readtemplte = new StreamReader(tpl_path);
        msgbox = new StringBuilder();
        msgbox_button = new ArrayList();

        while ((strLine = readtemplte.ReadLine()) != null)
        {
            msgbox.Append(strLine);
        }
    }

    public void SetTitle(string msg_title)
    {
        this.msgbox_title = msg_title;
    }

    public void SetIcon(string msg_icon)
    {
        this.msgbox_icon = "<img src=\"" + msg_icon + "\">";
    }

    public void SetMessage(string msg_message)
    {
        this.msgbox_message = msg_message;
    }

    public void SetOKButton(string msg_button_class)

    {
        this.msgbox_ok_button = "<input type=\"button\" value=\"OK\" class=\""
        + msg_button_class + 
        "\" onClick=\"document.getElementById('pagedimmer').style.visibility = 'hidden';" 
        + "document.getElementById('msgbox').style.visibility = 'hidden';\">";
    }

    public void AddButton(string msg_button)
    {
        msgbox_button.Add(msg_button);
    }

    public string ReturnObject()
    {
        int i=0;
        while (i < msgbox_button.Count)
        {
            msgbox_buttons += msgbox_button[i] + " ";
            i++;
        }

        msgbox.Replace("[TITLE]", this.msgbox_title);
        msgbox.Replace("[ICON]", this.msgbox_icon);
        msgbox.Replace("[MESSAGE]", this.msgbox_message);
        msgbox.Replace("[BUTTONS]", msgbox_buttons + this.msgbox_ok_button);

        return msgbox.ToString();
    }
}
Listing 1.8 - MessageBox class
C#
using System;
using System.Text;
using System.Web;
using System.Web.UI;

public class MessageBoxButton
{
    private string msg_button = "";

    public MessageBoxButton(string btnValue)
    {
        msg_button = "<input type=\"button\" value=\"" + btnValue + "\"";
    }

    public void SetClass(string btnClass)
    {
        msg_button += " class=\"" + btnClass + "\"";
    }

    public void SetLocation(string btnLocation)
    {
        msg_button += " onClick=\"window.location='" + btnLocation + "'\"";
    }

    public string ReturnObject()
    {
       return msg_button += ">";
    }
}
Listing 1.9 - MessageBoxButton class

Update: I've finally updated the MessageBox class and added a few more features such as custom variables for the template file. You can download the latest code from here.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)