处理 WebControl 内的按钮单击事件

发布于 2024-11-30 23:58:34 字数 6109 浏览 0 评论 0原文

我创建了一个自定义 WebControl,它实现了一个可以显示在网页顶部的简单消息框。类似于 YouTube 在其页面上显示消息的方式。我的问题是将 Click 事件从我添加到框中的任何按钮传递到 ASPX 页面。

下面是 WebControl 的代码。我认为我已经正确处理了单击事件,但是当我将此代码添加到页面时,单击事件永远不会被调用,尽管 Page_Load 会被调用。

这是 APSX 页面中的代码:

<rt:ConfirmationBox ID="ConfirmationBox1" runat="server" BoxType="Info" BoxButtons="OkayCancel" OnOkayClicked="ConfirmationBoxOkayClicked"
    Text="Click OK to close." />

这是代码隐藏页面中的代码:

protected void ConfirmationBoxOkayClicked(object sender, EventArgs e)
{
    ConfirmationBox1.BoxButtons = ConfirmationBoxButtons.None;
    ConfirmationBox1.BoxType = ConfirmationBoxType.Success;
    ConfirmationBox1.Text = "You clicked OK!";
}

这是 WebControl 代码:

public enum ConfirmationBoxType
{
    Hidden,
    Success,
    Warn,
    Error,
    Info
}

public enum ConfirmationBoxButtons
{
    None,
    Okay,
    Cancel,
    OkayCancel
}

[DefaultProperty("Text")]
[ToolboxData("<{0}:ConfirmationBox ID=\"ConfirmationBox1\" runat=server></{0}:ConfirmationBox>")]
public class ConfirmationBox : WebControl
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(ConfirmationBox));

    private Button _okayButton;
    private Button _cancelButton;

    public event EventHandler OkayClicked;
    public event EventHandler CancelClicked;

    public virtual void OnOkayClicked(object sender, EventArgs eventArgs)
    {
        if (OkayClicked != null)
            OkayClicked(sender, eventArgs);
    }

    public virtual void OnCancelClicked(object sender, EventArgs eventArgs)
    {
        if (CancelClicked != null)
            CancelClicked(sender, eventArgs);
    }

    protected override void OnPreRender(EventArgs e)
    {
        _okayButton = new Button {ID = "ConfirmBoxOkayButton", CssClass = "button", Text = "OK"};
        _okayButton.Click += new EventHandler(OnOkayClicked);

        _cancelButton = new Button {ID = "ConfirmBoxCancelButton", CssClass = "button", Text = "Cancel"};
        _cancelButton.Click += new EventHandler(OnCancelClicked);
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public string Text
    {
        get
        {
            var s = (String)ViewState["Text"];
            return (s ?? String.Empty);
        }

        set
        {
            ViewState["Text"] = value;
        }
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("Hidden")]
    public ConfirmationBoxType BoxType
    {
        get
        {
            return (ConfirmationBoxType)ViewState["BoxType"];
        }

        set
        {
            ViewState["BoxType"] = value;
        }
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("None")]
    public ConfirmationBoxButtons BoxButtons
    {
        get
        {
            return (ConfirmationBoxButtons)ViewState["BoxButtons"];
        }

        set
        {
            ViewState["BoxButtons"] = value;
        }
    }

    protected override HtmlTextWriterTag TagKey
    {
        get
        {
            return HtmlTextWriterTag.Div;
        }
    }

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Id, "alerts");
        base.AddAttributesToRender(writer);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        if (Site != null && Site.DesignMode)
        {
            writer.Write("[" + ID + "]");
        }
        else
        {
            if (BoxType == ConfirmationBoxType.Hidden)
                return;

            var theme = HttpContext.Current.Profile["UserTheme"].ToString();

            writer.AddAttribute(HtmlTextWriterAttribute.Id, "confirmBox");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert " + RenderBoxType());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Src, string.Format("{0}/{1}/pixel.gif", ResolveUrl("~/App_Themes"), (string.IsNullOrEmpty(theme)) ? "Default" : theme));
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "icon");
            writer.AddAttribute(HtmlTextWriterAttribute.Alt, "Alert icon");
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert-content");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.Write(Text);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "close");
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#alerts\").hide()");
            writer.RenderBeginTag(HtmlTextWriterTag.Button);
            writer.Write("close");
            writer.RenderEndTag();

            if (BoxButtons != ConfirmationBoxButtons.None)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert-buttons");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                if (BoxButtons == ConfirmationBoxButtons.Okay || BoxButtons == ConfirmationBoxButtons.OkayCancel)
                    _okayButton.RenderControl(writer);
                if (BoxButtons == ConfirmationBoxButtons.Cancel || BoxButtons == ConfirmationBoxButtons.OkayCancel)
                    _cancelButton.RenderControl(writer);
                writer.RenderEndTag();
            }

            writer.RenderEndTag();
        }
    }

    private string RenderBoxType()
    {
        switch (BoxType)
        {
            case ConfirmationBoxType.Success:
                return "rt-alert-success";
            case ConfirmationBoxType.Warn:
                return "rt-alert-warn";
            case ConfirmationBoxType.Error:
                return "rt-alert-error";
            case ConfirmationBoxType.Info:
                return "rt-alert-info";
        }

        return string.Empty;
    }
}

I've created a custom WebControl that implements a simple message box that can display at the top of a web page. Similar to how YouTube displays messages on their pages. My problem is passing the Click event from any button I add to the box down to the ASPX page.

Below is the code for the WebControl. I think I have handling the click events right, but when I add this code to my page, the click event never gets called, although Page_Load does.

Here's the code in the APSX page:

<rt:ConfirmationBox ID="ConfirmationBox1" runat="server" BoxType="Info" BoxButtons="OkayCancel" OnOkayClicked="ConfirmationBoxOkayClicked"
    Text="Click OK to close." />

Here's the code in the code behind page:

protected void ConfirmationBoxOkayClicked(object sender, EventArgs e)
{
    ConfirmationBox1.BoxButtons = ConfirmationBoxButtons.None;
    ConfirmationBox1.BoxType = ConfirmationBoxType.Success;
    ConfirmationBox1.Text = "You clicked OK!";
}

Here's the WebControl code:

public enum ConfirmationBoxType
{
    Hidden,
    Success,
    Warn,
    Error,
    Info
}

public enum ConfirmationBoxButtons
{
    None,
    Okay,
    Cancel,
    OkayCancel
}

[DefaultProperty("Text")]
[ToolboxData("<{0}:ConfirmationBox ID=\"ConfirmationBox1\" runat=server></{0}:ConfirmationBox>")]
public class ConfirmationBox : WebControl
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(ConfirmationBox));

    private Button _okayButton;
    private Button _cancelButton;

    public event EventHandler OkayClicked;
    public event EventHandler CancelClicked;

    public virtual void OnOkayClicked(object sender, EventArgs eventArgs)
    {
        if (OkayClicked != null)
            OkayClicked(sender, eventArgs);
    }

    public virtual void OnCancelClicked(object sender, EventArgs eventArgs)
    {
        if (CancelClicked != null)
            CancelClicked(sender, eventArgs);
    }

    protected override void OnPreRender(EventArgs e)
    {
        _okayButton = new Button {ID = "ConfirmBoxOkayButton", CssClass = "button", Text = "OK"};
        _okayButton.Click += new EventHandler(OnOkayClicked);

        _cancelButton = new Button {ID = "ConfirmBoxCancelButton", CssClass = "button", Text = "Cancel"};
        _cancelButton.Click += new EventHandler(OnCancelClicked);
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public string Text
    {
        get
        {
            var s = (String)ViewState["Text"];
            return (s ?? String.Empty);
        }

        set
        {
            ViewState["Text"] = value;
        }
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("Hidden")]
    public ConfirmationBoxType BoxType
    {
        get
        {
            return (ConfirmationBoxType)ViewState["BoxType"];
        }

        set
        {
            ViewState["BoxType"] = value;
        }
    }

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("None")]
    public ConfirmationBoxButtons BoxButtons
    {
        get
        {
            return (ConfirmationBoxButtons)ViewState["BoxButtons"];
        }

        set
        {
            ViewState["BoxButtons"] = value;
        }
    }

    protected override HtmlTextWriterTag TagKey
    {
        get
        {
            return HtmlTextWriterTag.Div;
        }
    }

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Id, "alerts");
        base.AddAttributesToRender(writer);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        if (Site != null && Site.DesignMode)
        {
            writer.Write("[" + ID + "]");
        }
        else
        {
            if (BoxType == ConfirmationBoxType.Hidden)
                return;

            var theme = HttpContext.Current.Profile["UserTheme"].ToString();

            writer.AddAttribute(HtmlTextWriterAttribute.Id, "confirmBox");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert " + RenderBoxType());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Src, string.Format("{0}/{1}/pixel.gif", ResolveUrl("~/App_Themes"), (string.IsNullOrEmpty(theme)) ? "Default" : theme));
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "icon");
            writer.AddAttribute(HtmlTextWriterAttribute.Alt, "Alert icon");
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert-content");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.Write(Text);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "close");
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#alerts\").hide()");
            writer.RenderBeginTag(HtmlTextWriterTag.Button);
            writer.Write("close");
            writer.RenderEndTag();

            if (BoxButtons != ConfirmationBoxButtons.None)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "rt-alert-buttons");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                if (BoxButtons == ConfirmationBoxButtons.Okay || BoxButtons == ConfirmationBoxButtons.OkayCancel)
                    _okayButton.RenderControl(writer);
                if (BoxButtons == ConfirmationBoxButtons.Cancel || BoxButtons == ConfirmationBoxButtons.OkayCancel)
                    _cancelButton.RenderControl(writer);
                writer.RenderEndTag();
            }

            writer.RenderEndTag();
        }
    }

    private string RenderBoxType()
    {
        switch (BoxType)
        {
            case ConfirmationBoxType.Success:
                return "rt-alert-success";
            case ConfirmationBoxType.Warn:
                return "rt-alert-warn";
            case ConfirmationBoxType.Error:
                return "rt-alert-error";
            case ConfirmationBoxType.Info:
                return "rt-alert-info";
        }

        return string.Empty;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

禾厶谷欠 2024-12-07 23:58:34

为您的自定义事件处理程序创建一个单独的方法,如下所示:

protected virtual void OnOkayClicked(EventArgs e)
{
    if (OkayClicked!= null)
        OkayClicked(this, e);
}

更改按钮单击事件的名称并使其受保护,如下所示:

protected void OkayButton_Click(object sender, EventArgs e)
{
     //call your event handler method
     this.OnOkayClicked(EventArgs.Empty);
}

测试一下,看看是否有区别。

Create a separate method for your custom event handler, like this:

protected virtual void OnOkayClicked(EventArgs e)
{
    if (OkayClicked!= null)
        OkayClicked(this, e);
}

Change the name of the button click event and make it protected, like this:

protected void OkayButton_Click(object sender, EventArgs e)
{
     //call your event handler method
     this.OnOkayClicked(EventArgs.Empty);
}

Test this out, and see if it makes a difference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文