Button的OnClick事件不会触发

时间:2010-11-28 06:28:51

标签: c# asp.net events click web-controls

以下代码是我的ASP.NET页面:

<MdsMenu:MenuItem Text="Button" Href="#">
   <asp:Button ID="Button1" runat="server" Text="Button 01" OnClick="Button_Click" />
   <asp:Button ID="Button2" runat="server" Text="Button 02" OnClick="Button_Click" />
</MdsMenu:MenuItem>

我不知道为什么Button_Click事件不会触发!!!

protected void Button_Click(object sender, EventArgs e)
{
   Button senderButton = sender as Button;
   Label1.Text = senderButton.ID.ToString();
}

MdsMenu:MenuItem 是我的自定义WebControl。 如果我从MdsMenu:MenuItem标签插入一个Button控件,它可以很好地工作,但如果我将它插入MdsMenu:MenuItem标签,它不会触发相关的方法。 我的代码出了什么问题?

感谢。

修改

Menu.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Collections;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Web.UI.HtmlControls;
using System.IO;

namespace MenuServerControl
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("MenuItems")]
    [ParseChildren(true, "MenuItems")]
    [ToolboxData("<{0}:Menu runat=\"server\"> </{0}:Menu>")]
    public class Menu : WebControl
    {
        #region Fields

        private List<MenuItem> _MenuItems;
        string _Direction
        {
            get
            {
                string direction = "";
                switch (this.Direction)
                {
                    case Directions.LeftToRight:
                        direction = "direction:ltr;";
                        break;
                    case Directions.RightToLeft:
                        direction = "direction:rtl;";
                        break;
                    default:
                        direction = "direction:rtl;";
                        break;
                }
                return direction;
            }
        }
        string _AnimationDelay
        {
            get
            {
                if (AnimationDelay == null)
                    AnimationDelay = 1000;
                return AnimationDelay.ToString().ToLower();
            }
        }
        string _AnimationType
        {
            get
            {
                switch (this.AnimationType)
                {
                    case AnimationType.Opacity_Height:
                        return "animation:{opacity:'show',height:'show'}";
                    case AnimationType.Opacity_Width:
                        return "animation:{opacity:'show',width:'show'}";
                    case AnimationType.Opacity:
                        return "animation:{opacity:'show'}";
                    case AnimationType.Height:
                        return "animation:{height:'show'}";
                    case AnimationType.Width:
                        return "animation:{width:'show'}";
                    case AnimationType.Height_Toggle:
                        return "animation: {height: 'toggle'}";
                    case AnimationType.Width_Toggle:
                        return "animation: {width: 'toggle'}";
                    default:
                        return "animation:{opacity:'show',height:'show'}";
                }
            }
        }
        string _AnimationSpeed
        {
            get
            {
                switch (this.AnimationSpeed)
                {
                    case AnimationSpeed.Fast:
                        return "speed:'fast'";
                    case AnimationSpeed.Normal:
                        return "speed:'normal'";
                    case AnimationSpeed.Slow:
                        return "speed:'slow'";
                    default:
                        return "speed:'fast'";
                }
            }
        }
        string FloatStyle
        {
            get
            {
                if (Direction == Directions.RightToLeft)
                    return "float:right;";
                else return "";
            }
        }
        string _Main_ul_CssClass = "";

        #endregion

        #region Properties

        public string Main_ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_Main_ul_CssClass)) return "";
                _Main_ul_CssClass = "class=" + _Main_ul_CssClass;
                return _Main_ul_CssClass;
            }

            set
            {
                _Main_ul_CssClass = value.Trim();
            }
        }

        public Directions Direction { get; set; }

        public int? AnimationDelay { get; set; }

        public AnimationType AnimationType { get; set; }

        public AnimationSpeed AnimationSpeed { get; set; }

        public bool DropShadow { get; set; }

        public bool AutoArrows { get; set; }

        [Category("Behavior")]
        [Description("The menu collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public List<MenuItem> MenuItems
        {
            get
            {
                if (_MenuItems == null)
                    _MenuItems = new List<MenuItem>();
                return _MenuItems;
            }
        }

        public VerOrHor VerticalOrHorizontal { get; set; }

        #endregion

        #region Methods

        public Menu()
        {
            DropShadow = true;
            AutoArrows = true;
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.Write("<div id=\"" + this.ID + "\" style=\"" + _Direction + " " + FloatStyle + "\">");
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.Write("</div>");
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            #region Adding Script & link Tags

            HtmlGenericControl jquery = new HtmlGenericControl("script");
            jquery.Attributes.Add("type", "text/javascript");
            jquery.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(MenuServerControl.Menu), "MenuServerControl.JavaScriptFiles.jquery_1_4_3.js"));
            jquery.EnableViewState = false;
            Page.Header.Controls.Add(jquery);

            HtmlGenericControl hoverIntent = new HtmlGenericControl("script");
            hoverIntent.Attributes.Add("type", "text/javascript");
            hoverIntent.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.hoverIntent.js"));
            hoverIntent.EnableViewState = false;
            Page.Header.Controls.Add(hoverIntent);

            HtmlGenericControl jquery_bgiframe_min = new HtmlGenericControl("script");
            jquery_bgiframe_min.Attributes.Add("type", "text/javascript");
            jquery_bgiframe_min.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.jquery_bgiframe_min.js"));
            jquery_bgiframe_min.EnableViewState = false;
            Page.Header.Controls.Add(jquery_bgiframe_min);

            HtmlGenericControl superfish = new HtmlGenericControl("script");
            superfish.Attributes.Add("type", "text/javascript");
            superfish.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.superfish.js"));
            superfish.EnableViewState = false;
            Page.Header.Controls.Add(superfish);

            HtmlGenericControl supersubs = new HtmlGenericControl("script");
            supersubs.Attributes.Add("type", "text/javascript");
            supersubs.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.supersubs.js"));
            supersubs.EnableViewState = false;
            Page.Header.Controls.Add(supersubs);

            if (Direction == Directions.LeftToRight)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }
            else
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }

            if (this.VerticalOrHorizontal == VerOrHor.Vertical && this.Direction == Directions.RightToLeft)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }
            else if (this.VerticalOrHorizontal == VerOrHor.Vertical)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }

            #endregion
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(CreateMenuHtmlTags());
        }

        StringBuilder CreateMenuHtmlTags()
        {
            if (this._MenuItems == null)
                throw new Exception("تگ های مربوط به منو را کامل کنید");

            StringBuilder Html = new StringBuilder("");

            #region Add <Script>

            if (String.IsNullOrEmpty(Main_ul_CssClass))
                Html.Append("<script>$(document).ready(function() { $(\"ul.sf-menu\").superfish({pathLevels:    1,");
            else
                Html.Append("<script>$(document).ready(function() { $(\"ul." + Main_ul_CssClass + "\").superfish({ pathLevels:    1,");

            Html.Append("delay:" + _AnimationDelay + ",");
            Html.Append(_AnimationType + ",");
            Html.Append(_AnimationSpeed + ",");
            Html.Append("dropShadows:  " + DropShadow.ToString().ToLower() + ",");
            Html.Append(@"autoArrows:  " + AutoArrows.ToString().ToLower() + "});});</script>");

            #endregion

            if (string.IsNullOrEmpty(Main_ul_CssClass) && VerticalOrHorizontal == VerOrHor.Vertical)
                Html.Append("<ul class=\"sf-menu sf-vertical sf-js-enabled sf-shadow\" id='sample-menu-1'>");
            else if (String.IsNullOrEmpty(Main_ul_CssClass))
                Html.Append("<ul class=\"sf-menu sf-js-enabled sf-shadow\" id='sample-menu-1'>");
            else
                Html.Append("<ul class=\"" + Main_ul_CssClass + "\" id='sample-menu-1'>");

            foreach (MenuItem item in _MenuItems)
            {
                if (item == null) continue;
                if (item.SubMenuItems != null && item.SubMenuItems.Count > 0)
                {
                    Html.Append("<li" + item.li_CssClass + ">");
                    Html.Append("<a href=\"" + item.Href + "\">" + item.Text.Trim() + "</a>");
                    ParseSubMenuItems(ref Html, item);
                    Html.Append("</li>");
                }
                else if (item.SubMenuItems != null)
                    Html.Append("<li" + item.li_CssClass + "><a href=\"" + item.Href + "\">" + item.Text.Trim() + "</a></li>");
            }
            Html.Append("</ul>");

            return Html;
        }

        void ParseSubMenuItems(ref StringBuilder Html, MenuItem menuItems)
        {
            if (menuItems == null) return;

            Html.Append("<ul " + menuItems.ul_CssClass + " style=\"display: none; visibility: hidden;\">");

            foreach (var item in menuItems.SubMenuItems)
            {
                if (item == null) continue;

                MenuItem Sub_MenuItem = item as MenuItem;
                WebControl webControl = item as WebControl;

                if (Sub_MenuItem != null)
                {
                    if (Sub_MenuItem.SubMenuItems != null && Sub_MenuItem.SubMenuItems.Count > 0)
                    {
                        Html.Append("<li" + Sub_MenuItem.li_CssClass + ">");
                        Html.Append("<a href=\"" + Sub_MenuItem.Href + "\">" + Sub_MenuItem.Text.Trim() + "</a>");
                        ParseSubMenuItems(ref Html, Sub_MenuItem);
                        Html.Append("</li>");
                    }
                    else if (Sub_MenuItem.SubMenuItems != null)
                        Html.Append("<li" + Sub_MenuItem.li_CssClass + "><a href=\"" + Sub_MenuItem.Href + "\">" + Sub_MenuItem.Text.Trim() + "</a></li>");
                }
                else if (webControl != null)
                {
                    Html.Append("<li>");
                    webControl.EnableViewState = true;
                    this.Controls.Add(webControl);
                    webControl.EnableViewState = true;

                    StringBuilder sb = new StringBuilder();
                    sb.Append("<div>");
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
                        {
                            webControl.RenderControl(textWriter);
                        }
                    }

                    sb.Append("</div>");

                    Html.Append(sb.ToString());
                    Html.Append("</li>");
                }
            }
            Html.Append("</ul>");
        }

        #endregion
    }
}

MenuItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace MenuServerControl
{
    [DefaultProperty("SubMenuItems")]
    [ParseChildren(true, "SubMenuItems")]
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class MenuItem : INamingContainer
    {
        #region Fields

        ArrayList _SubMenuItems;
        string text = "";
        string href = "#";
        string _ul_CssClass = "";
        string _li_CssClass = "";

        #endregion

        #region Properties

        [Description("متن منو آیتم")]
        [DefaultValue("")]
        [NotifyParentProperty(true)]
        public string Text
        {
            get
            {
                return text;
            }

            set
            {
                text = value;
            }
        }

        [DefaultValue("#")]
        [Description("<a /> href attribute")]
        [NotifyParentProperty(true)]
        public string Href
        {
            get
            {
                return href;
            }

            set
            {
                href = value;
            }
        }

        [DefaultValue("")]
        [Description("<ul /> css class")]
        [NotifyParentProperty(true)]
        public string ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_ul_CssClass)) return "";
                _ul_CssClass = " class=\"" + _ul_CssClass + "\"";
                return _ul_CssClass;
            }
            set { this._ul_CssClass = value.Trim(); }
        }

        [DefaultValue("")]
        [Description("<li /> css class")]
        [NotifyParentProperty(true)]
        public string li_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_li_CssClass)) return "";
                _li_CssClass = " class=\"" + _li_CssClass + "\"";
                return _li_CssClass;
            }
            set { this._li_CssClass = value.Trim(); }
        }

        [Category("Behavior")]
        [Description("The MenuItems collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public ArrayList SubMenuItems
        {
            get
            {
                if (_SubMenuItems == null)
                    _SubMenuItems = new ArrayList();
                return _SubMenuItems;
            }
        }

        #endregion
    }
}

您可以从here下载项目。

1 个答案:

答案 0 :(得分:1)

步骤1:在.aspx页面本身中具有隐藏按钮,其中包含控件的所需OnClick 外部,例如

<asp:Button ID="Button1" runat="server" OnClick="Button_Click" style="display: none;"  />

步骤2:在控件内的按钮中使用OnClientClick,如下所示:

<asp:Button ID="SomeIdHere" runat="server" Text="Button 01" OnClientClick="return MakeRealClick('Button1');" />

确保将“真实”按钮的ID作为“MakeRealClick”功能的参数。

步骤3:在页面中包含此JavaScript代码:

<script type="text/javascript">
    function MakeRealClick(sButtonID) {
        var arrInputs = document.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oCurInput = arrInputs[i];
            if (oCurInput.type == "submit" && (oCurInput.id == sButtonID || EndsWith(oCurInput.id, "_" + sButtonID)))
                oCurInput.click();
        }
        return false;
    }

    function EndsWith(s1, s2) {
        return (s1.length >= s2.length) && (s1.substr(s1.length - s2.length, s2.length) == s2);
    }
</script>

这将导致单击时,菜单中的按钮将搜索菜单外的其他按钮,因此仍然具有“真实”OnClick,并自动单击它以使最终结果与单击隐藏时相同按钮。

非常确定有更好的方法,但就像我说的那样:快速修复代码的最小变化。