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

Message Box Control

4.91/5 (25 votes)
29 Oct 2013CPOL3 min read 61.9K   2.3K  
A message box that can be drawn with HTML and CSS.

Introduction

Most applications, or all of them, require a mechanism to notify the user when necessary. In Windows applications, a MessageBox[^] can solve this issue by providing a modal dialog with:

  • a title that can represent the source of the message
  • an icon for each message type to determine how critical a message box is
  • a brief text message
  • some command buttons that can represent a user decision
  • and a unique system sound that tells how critical a message box is
save cofirmation

Unfortunately, in web applications, this feature doesn't exist. This is replaced with JavaScript alert() and confirm() which cannot be controlled by the designer.

alert confirm

In this article, we are going to introduce a message box that looks like the Windows application one but with extra design features and some behaviors that deal with the web environment.

Style1 Style1

Background

This article is based on the concepts discussed on Confirm Message Box[^] with some features from the System.Windows.Forms.MessageBox[^] class.

Using the Code

The control, just like System.Windows.Forms.MessageBox[^], provides Show() method overloads, and also it provides RegisterButtonForShowigMessage() with an additional parameter to hold the button reference.

The control also provides three extra parameters of type MessageBoxButtonAction which has four values:

  • Undefined: for doing nothing
  • AcceptDialog: for re-firing the post-back event of the calling button
  • Close: for closing the dialog and raising
    ClientResultReturn
    event on the Client-Side
  • PostBack: for closing the dialog and raising ResultReturn event on the Server-Side

The control also provides eight properties of type String to customize the text on the buttons.

  • OKButtonText: for the "OK" command button text
  • CancelButtonText: for the "Cancel" command button text
  • AbortButtonText: for the "Abort" command button text
  • RetryButtonText: for the "Retry" command button text
  • IgnoreButtonText: for the "Ignore" command button text
  • YesButtonText: for the "Yes" command button text
  • NoButtonText: for the "No" command button text
  • and CloseButtonText: for the dialog close button text

You can use the control just like:

C#
MessageBox MessageBox1 = MessageBox.GetCurrent(this);
MessageBox1.OnClientResultReturn = "OnCloseDialig";

MessageBox1.RegisterButtonForShowigMessage(cmdClose, 
  "Do you want to save this transaction before exiting the page?",
  "My Application", "Exit", MyControls.MessageBoxButtons.YesNoCancel,
  MyControls.MessageBoxIcon.Exclamation, MyControls.MessageBoxDefaultButton.Button1,
  MyControls.MessageBoxButtonAction.PostBack,
  MyControls.MessageBoxButtonAction.PostBack, 
  MyControls.MessageBoxButtonAction.Close);

You can also add a JavaScript function that handles ClientResultReturn event just like:

JavaScript
function OnCloseDialig(sender, e) {
    var args = sender.get_Tag().split(',');

    if (args[0] == 'Copy')
        if (e.get_DialogResult() == MyControls.DialogResult.Abort ||
        e.get_DialogResult() == MyControls.DialogResult.OK)
        $get('<%= loader.ClientID %>').style.display = 'none';
}

This method would be invoked just after the message box gets closed.

To handle the server-side event ResultReturn of the control, you just need to add a handler to the event. In the handling method, you use the Tag property of th for the message source and also DialogResult property of the event argument. For example:

C#
void MessageBox1_ResultReturn(object sender, MessageBoxEventArgs e)
{
    MessageBox MessageBox1 = (sender as MessageBox );

    string[] args = MessageBox1.Tag.Split(new char[] { ',' },
			StringSplitOptions.RemoveEmptyEntries);

    string command = string.Empty;
    string[] commandargs = null;

    if (args.Length > 0)
        command = args[0];

    if (args.Length > 1)
    {
        commandargs = new string[args.Length - 1];
        for (int i = 1; i > args.Length; i++)
            commandargs[i - 1] = args[i];
    }

    switch (command)
    {
        case "Copy":
            ContiueCoping(e.DialogResult, commandargs[0]);
            break;
        case "Exit":
            ExitPage(e.DialogResult);
            break;
    }
}

Finally, to get a referer of OpenDialog() function to be added to a script block, we can call the method GetOpenDialogReference() with the same parameters as Show() discussed above. As following:

C#
StringBuilder validateSelectionBuilder = new StringBuilder();
validateSelectionBuilder.AppendLine("function ValidateSelection(sender, e){");
validateSelectionBuilder.AppendLine("    var count = getCheckedItemsCount('AddItems');");
validateSelectionBuilder.AppendLine(string.Format(
  "  if(count == 0) {{ {0} e.IsValid = false; }}", 
  MessageBox1.GetOpenDialogReference("Please select at least one item.", 
  "My Application", "AddItems", 
  MessageBoxButtons.OK, MessageBoxIcon.Exclamation, 
  MessageBoxDefaultButton.Button1, 
  new MessageBoxButtonsAcionProvider(MessageBoxButtonAction.Close))));

validateSelectionBuilder.AppendLine(string.Format(
  "  else if(count > 3) {{ {0} e.IsValid = false; }}", 
  MessageBox1.GetOpenDialogReference(
  "You can not add more than three items at a time.", "My Application", 
  "AddItems", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, 
  MessageBoxDefaultButton.Button1, 
  new MessageBoxButtonsAcionProvider(MessageBoxButtonAction.Close))));

validateSelectionBuilder.AppendLine("    else e.IsValid = true;");
validateSelectionBuilder.AppendLine("}");

Points of Interest

Unlike Confirm Message Box[^], we don't need to keep more than one instance of the message box object. So we first add the object to Page.Items Collection within OnInit() method.

C#
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    if (!base.DesignMode)
    {
        if (GetCurrent(this.Page) != null)
        {
            throw new InvalidOperationException(
              "Only One MessageBox instance is allowed.");
        }
        Page iPage = this.Page;
        iPage.Items[typeof(MessageBox)] = this;
    }
}

After that, we use this collection from any content page whose master contains the control or even a control in the page by using MessageBox.GetCurrent() method.

C#
public static MessageBox  GetCurrent(Page page)
{
    if (page == null)
    {
        throw new ArgumentNullException("page");
    }
    return (page.Items[typeof(MessageBox)] as MessageBox);
}

History

  • Saturday, May 14, 2011
    • First version.
  • Sunday, May 15, 2011
    • Paragraph describing ClientResultReturn was added
  • Monday, June 6, 2011
    • Added a paragraph to describe event ResultReturn
    • Changed the HTML layout of the control
    • Fixed the default style of the control
    • Added a sample .htm file
    • Fixed the JavaScript function OpenDialog() in the compatibility view
    • Fixed the JavaScript function AcceptDialog() behavior when the
      Show()
      
      method is called from the server-side
  • Sunday, October 30, 2011
    • Changed the introduction of the article
    • Fixed the JavaScript errors on Google Chrome
    • Added the method GetOpenDialogReference() and a paragraph describing it
  • Thursday, March 22, 2012
    • Fixed style problem in IE6.
    • Edited the examples to include globalization.

License

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