65.9K
CodeProject 正在变化。 阅读更多。
Home

一个简单的事件驱动确认框/消息框服务器控件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.83/5 (9投票s)

2006 年 4 月 21 日

CPOL

2分钟阅读

viewsIcon

70202

downloadIcon

910

一篇关于消息框服务器控件的文章,该控件可以在服务器端捕获确认框的按钮按下事件。

MessageBox Server control

引言

ASP.NET 2.0 提供了几个服务器控件,但仍然缺少消息框、确认框等。 有一个优秀的服务器控件是由Ning Liao, Liang Yang开发的,你可以在CodeProject上找到它。 但我猜这还不够; 你需要在这个模型中以编程方式检查所有内容。 因此,我开发了这个事件驱动的服务器控件,它在客户端确认框的按钮点击时触发一个GetMessageBoxRespose事件。 您可以在此事件中捕获按下了哪个按钮。 当用户按下按钮时,页面会再次发布,状态会丢失,并且我们需要再次获取我们正在处理的任何数据。 因此,我提供了一个在确认时传递数据的机制,我们可以在触发的事件中获取它。 很好,不是吗?

Using the Code

要在代码中使用服务器控件,您需要将服务器控件作为.NET Framework 组件添加到您的 Web 应用程序中。 右键单击工具箱中的“组件”选项卡,单击“添加/删除项目”,单击“浏览”,然后选择并添加服务器控件 MessageBox.dll,从您将其保存在计算机上的位置。 然后,将服务器控件拖放到您的 Web 表单中。 以下是包含服务器控件的 Default.aspx 代码

//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" />

要显示确认框,只需调用 msgBox 对象的 Confirm 方法,如下所示

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.");
    }
}

当用户通过单击“确定”或“取消”按钮来响应确认框时,Web 页面将发布回发。 在回发后,MessageBox 控件将触发 GetMessageBoxResponse 事件,因此您需要通过注册其事件处理程序来捕获此事件。 在此事件中,您将获得用户按下了哪个按钮以及通过 Confirm 方法传递的其他数据

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);
    }
}

关于 MessageBox 控件

MessageBox 服务器控件的基本机制实际上非常简单。 由于它是完全事件驱动的,因此它带来的便利是巨大的。 使用 Confirm 方法进行确认并捕获 GetMessageBoxResponse 事件。 获取用户按下的按钮以及通过 Confirm 方法传递的其他数据。 我很欣赏 Ning Liao, Liang Yang 的工作; 这些家伙做得很好,但我认为这比他们的工作有所改进,不是吗?

源代码

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>");
            }
        }
    }
}
© . All rights reserved.