Click here to Skip to main content
15,885,278 members
Articles / Web Development / IIS

A Simple Event Driven Confirmation Box / Messege Box Server Control

Rate me:
Please Sign up or sign in to vote.
3.83/5 (9 votes)
21 Apr 2006CPOL2 min read 68.4K   870   30   16
An article on a MessageBox server control that can capture a confirmation box's button pressed event on the server side.

MessageBox Server control

Introduction

ASP.NET 2.0 provides several server controls, but it still lacks a Message Box, Confirmation Box, etc. There is an excellent server control developed by Ning Liao, Liang Yang which you will get on CodeProject itself. But I guess it's not sufficient; you need to programmatically check everything in this model. So I developed this event driven server control which raises a GetMessageBoxRespose event on the button click of the client-side confirmation box. You can capture which button is pressed in this event. As the user presses the button, the page gets posted again and the state gets lost and whatever data we were processing needs to get back again. Hence, I made a provision to pass data while confirming, and we can get it back in the raised event. It's cool, isn't it?

Using the Code

To use the server control in your code, you need to add the server control as a .NET Framework Component to your web application. Right click the "Components" tab in the toolbox, click "Add/Remove Items," click "Browse", and select and add the server control MessageBox.dll from where you keep it in your computer. Then, drag and drop the server control to your web form. The following is the Default.aspx code with the server control included:

ASP.NET
//First register Assembly with following line,
// If you drag drop control it will be done automatically.
<%@ Register Assembly="MessageBox" 
    Namespace="Utilities" TagPrefix="cc2" %>
    
//Add message box control
<cc2:MessageBox ID="msgBox" runat="server" 
      Style="z-index: 101; left: 0px; position: absolute; top: 0px" 
      Width="112px" 
      OnGetMessageBoxResponse="msgBox_GetMessageBoxResponse" />

To display the confirmation box, just call the Confirm method of the msgBox object, as shown below:

C#
private void Page_Load(object sender, System.EventArgs e)
{
    if( !IsPostBack )
    {
        //Display confirmation box at client side
        msgBox.Confirm("This control is cool isn't it?", "Test Data");
        //msgBox.Confirm("This control is cool isn't it?");
    }
    else    
    {
        msgBox.Alert("Page posback happened.");
    }
}

When the user responds to the confirmation box by clicking either the "OK" or the "Cancel" button, the web page will be posted back. After postback, the MessageBox control will raise the GetMessageBoxResponse event, so you need to capture this event by registering its event handler. In this event, you will get which button is pressed by the user and other data, if passed, with the Confirm method:

C#
private void msgBox_GetMessageBoxResponse(object sender, 
        Utilities.MessageBox.MessageBoxEventHandler e)
{
    if( e.ButtonPressed == 
        Utilities.MessageBox.MessageBoxEventHandler.Button.Ok )
    {
        lblMsg.Text = "You said ok. Thanks!!!";
    }
    else if (e.ButtonPressed == 
         Utilities.MessageBox.MessageBoxEventHandler.Button.Cancel)
    {
        lblMsg.Text = "You said cancel. :(";
    }
    if (e.Data != null) 
    { 
        Response.Write(e.Data);
    }
}

About the MessageBox Control

The basic mechanism of the MessageBox server control is actually very simple. As it is totally event-driven, the convenience it brings is tremendous. Use the Confirm method for confirmation and catch the GetMessageBoxResponse event. Get which button is pressed by the user and other data if passed with the Confirm method. I appreciate the work of Ning Liao, Liang Yang; these guys have done a great job, but I guess this is an improvement over their work, isn't it?

Source Code

C#
namespace Utilities
{
    /// <summary>
    /// Summary description for MessageBox.
    /// </summary>
    [ToolboxData("<{0}:MessageBox runat="\""server\"></{0}:MessageBox>")]
    [System.Serializable(), DesignTimeVisible()]
    public class MessageBox : System.Web.UI.WebControls.WebControl
    {
        private string m_Session = "msgSession";

        //Event Arguments from MessageBox response
        public class MessageBoxEventHandler : System.EventArgs
        {
            public enum Button
            {
                Ok, Cancel, NotPressed
            }
            public readonly MessageBoxEventHandler.Button ButtonPressed;
            public readonly object Data;
            public MessageBoxEventHandler(
                   MessageBoxEventHandler.Button buttonPressed)
                   : this(buttonPressed, null)
            {
            }
            public MessageBoxEventHandler(MessageBoxEventHandler.Button 
                   buttonPressed, object data)
            {
                this.ButtonPressed = buttonPressed;
                this.Data = data;
            }
        }

        public delegate void Message(object sender, 
                        MessageBoxEventHandler e);
        
        //Declare event to pass message box response
        public event Message GetMessageBoxResponse;
        //private string msg;
        private string content;

        private const string ok = "ok";
        private const string cancel = "cancel";
        private const string notPressed = "notPressed";

        public void Alert(string message)
        {
            string msg = message.Replace("\n", "\\n");
            msg = message.Replace("\"", "'");

            StringBuilder sb = new StringBuilder(50);
            sb.Append(@"<script language="'javascript'">");
            sb.Append(@"alert( """ + msg + @""" );");
            sb.Append(@"</script>");
            content = sb.ToString();
        }
                
        public void Confirm(string message)
        {   
            this.Confirm(message, null);
        }

        /// <summary>
        /// Displays confirmation box on client side
        /// </summary>
        /// <param name="message">Message to
        /// display on confirmation box</param>
        /// <param name="data">Data to pass
        /// to GetMessageBoxResponse event.</param>
        public void Confirm(string message, object data)
        {
            string msg = message.Replace("\n", "\\n");
            msg = message.Replace("\"", "'");

            StringBuilder sb = new StringBuilder(100);

            sb.AppendFormat(@"<input type='hidden' value='{0}' name='" 
                 + HiddenFieldName + "' />", MessageBox.notPressed);

            sb.Append(
                 @"<script language="'javascript'" type='text/javascript'>");

            sb.Append(@" if(confirm( """ + msg + @""" ))");
            sb.Append(@" { ");
            sb.Append("document.forms[0]." + HiddenFieldName + 
               ".value='" + MessageBox.ok + "';" + 
               "document.forms[0].submit(); }");
            sb.Append(@" else { ");
            sb.Append("document.forms[0]." + HiddenFieldName + 
               ".value='" + MessageBox.cancel + 
               "'; document.forms[0].submit(); }");

            sb.Append(@"</script>");

            content = sb.ToString();
            if (data != null)
            {
                this.Page.Session[m_Session + this.ClientID] = data;
            }
        }

        private string HiddenFieldName
        {
            get
            {
                return "hidF" + this.ID;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            object data = null;
            
            switch (this.Page.Request.Form[HiddenFieldName])
            {
                case MessageBox.ok:
                    this.Page.Request.Form[HiddenFieldName].Replace(
                         MessageBox.ok, MessageBox.notPressed);
                    if (this.Page.Session[m_Session + this.ClientID] != null)
                    {
                        data = this.Page.Session[m_Session + this.ClientID];
                        this.Page.Session.Remove(m_Session + this.ClientID);
                    }
                    OnMessageBoxShow(new MessageBoxEventHandler(
                         MessageBoxEventHandler.Button.Ok, data));
                    break;
                case MessageBox.cancel:
                    this.Page.Request.Form[HiddenFieldName].Replace(
                          MessageBox.cancel, MessageBox.notPressed);
                    if (this.Page.Session[m_Session + this.ClientID] != null)
                    {
                        data = this.Page.Session[m_Session + this.ClientID];
                        this.Page.Session.Remove(m_Session + this.ClientID);
                    }
                    OnMessageBoxShow(new MessageBoxEventHandler(
                         MessageBoxEventHandler.Button.Cancel, data));
                    break;
                case MessageBox.notPressed:
                    break;
                
                default:
                    break;
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// Invokes registered event handlers 
        /// with MessageBox class's object.
        /// </summary>
        /// <param name="e">Pass MessageBox event
        /// arguments to registered event handlers</param>
        protected virtual void OnMessageBoxShow(MessageBoxEventHandler e)
        {
            if (GetMessageBoxResponse != null)
            {
                GetMessageBoxResponse(this, e);
            }
        }

        protected override void Render(HtmlTextWriter output)
        {
            if (!this.DesignMode)
            {
                output.Write(this.content);
            }
            else
            {
                System.Web.UI.WebControls.Label lbl = new Label();
                lbl.Font.Bold = this.Font.Bold;
                lbl.Font.Italic = this.Font.Italic;
                lbl.Font.Names = this.Font.Names;
                lbl.Font.Overline = this.Font.Overline;
                lbl.Font.Size = this.Font.Size;
                lbl.Font.Strikeout = this.Font.Strikeout;
                lbl.Font.Underline = this.Font.Underline;

                lbl.ForeColor = this.ForeColor;
                lbl.BackColor = this.BackColor;
                lbl.BorderColor = this.BorderColor;
                lbl.BorderStyle = this.BorderStyle;
                lbl.BorderWidth = this.BorderWidth;
                lbl.Text = this.ID;
                lbl.RenderControl(output);
                //-- output.Write("<div style=\"font-size:medium;
                //   color:Blue; font-family:Verdana; font-size:8pt;
                // font-weight:bold;\">"+ this.ID +"</div>");
            }
        }
    }
}

License

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



Comments and Discussions

 
GeneralMy vote of 4 Pin
Nyein Nyein Chan Chan29-Aug-12 15:50
Nyein Nyein Chan Chan29-Aug-12 15:50 
QuestionDynamically Add GetMessageBoxResponse Event Pin
Nyein Nyein Chan Chan28-Aug-12 23:25
Nyein Nyein Chan Chan28-Aug-12 23:25 
QuestionProblem using messagebox Pin
SilkCode18-May-09 23:16
SilkCode18-May-09 23:16 
GeneralRe: Problem using messagebox Pin
Vaibhav Gawali19-May-09 22:07
Vaibhav Gawali19-May-09 22:07 
GeneralRe: Problem using messagebox Pin
synkaten2-Jun-09 10:18
synkaten2-Jun-09 10:18 
GeneralRe: Problem using messagebox Pin
SilkCode5-Jun-09 18:02
SilkCode5-Jun-09 18:02 
GeneralRe: Problem using messagebox Pin
Vaibhav Gawali8-Jun-09 23:26
Vaibhav Gawali8-Jun-09 23:26 
GeneralUpdatePanel !! Pin
airbase2-Dec-08 3:47
airbase2-Dec-08 3:47 
GeneralGood work! Pin
Scott Spradlin11-Apr-08 3:10
Scott Spradlin11-Apr-08 3:10 
GeneralRe: Good work! Pin
Vaibhav Gawali11-Apr-08 3:26
Vaibhav Gawali11-Apr-08 3:26 
GeneralMessagebox only work on Load_Page Pin
Seabert2-Nov-06 7:53
Seabert2-Nov-06 7:53 
QuestionMessageBox doesn't open Pin
p-coder6-Oct-06 4:26
p-coder6-Oct-06 4:26 
Generalpage gone when messagebox displayed Pin
sonali Aurangabadkar12-Sep-06 1:50
sonali Aurangabadkar12-Sep-06 1:50 
GeneralWrong assumptions Pin
nsimeonov25-Apr-06 9:02
nsimeonov25-Apr-06 9:02 
GeneralRe: Wrong assumptions Pin
Vaibhav Gawali25-Apr-06 23:21
Vaibhav Gawali25-Apr-06 23:21 
GeneralRe: Wrong assumptions Pin
synkaten3-Jun-09 7:37
synkaten3-Jun-09 7:37 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.