按钮的 OnClick 事件未触发

发布于 2024-10-04 23:52:45 字数 18092 浏览 7 评论 0原文

以下代码是我的 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
    }
}

您可以从此处下载该项目< /a>.

The following code is my ASP.NET page :

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

I don't know why Button_Click event doesn't fire !!!

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

MdsMenu:MenuItem is my custom WebControl.
If I insert a Button control out of MdsMenu:MenuItem tag it works well but if I inserted it within MdsMenu:MenuItem tag it doesn't fire the concerned method.
What's wrong with my code ?

Thanks.

Edit:

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

You can download the project from here.

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

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

发布评论

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

评论(1

对岸观火 2024-10-11 23:52:45

步骤#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,并自动单击它,因此最终结果与单击隐藏按钮相同。

很肯定有更好的方法,但就像我说的:以最小的代码更改进行快速修复。

Step #1: have hidden button with the desired OnClick outside of the control, in the .aspx page itself e.g.

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

Step #2: have OnClientClick in the button inside the control, like this:

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

Make sure to put the ID of the "real" button as the argument for "MakeRealClick" function.

Step #3: have this JavaScript code in the page:

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

This will cause that when clicked, the button inside the menu will search for other button that is outside the menu thus still has "real" OnClick, and auto click it so the final result is the same as if you clicked the hidden button.

Pretty sure there's better way, but like I said: quick fix with minimal change in code.

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