How to remove span tag from WebControl when rendered

后端 未结 15 978
生来不讨喜
生来不讨喜 2020-12-31 03:34

When using an ASP.NET CheckBox (and in out case, inherited from a CheckBox) it renders a span around the checkbox input control, this span control

15条回答
  •  心在旅途
    2020-12-31 04:16

    I spent the last 3 hours pulling my hair to find a solution at this problem.

    Here is what came out:

    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    /// 
    /// Represents a custom checkbox web control.
    /// Prevents itself to be wrapped into a  tag when disabled.
    /// 
    public class CustomCheckBox : CheckBox
    {
        /// 
        /// Renders the control to the specified HTML writer.
        /// 
        /// The HtmlTextWriter object that receives the control content.
        protected override void Render(HtmlTextWriter writer)
        {
            // Use custom writer
            writer = new HtmlTextWriterNoSpan(writer);
    
            // Call base class
            base.Render(writer);
        }
    }
    

    Along with the custom control, you'll need a custom HtmlTextWriter:

    using System.IO;
    using System.Web.UI;
    
    /// 
    /// Represents a custom HtmlTextWriter that displays no span tag.
    /// 
    public class HtmlTextWriterNoSpan : HtmlTextWriter
    {
        /// 
        /// Constructor.
        /// 
        /// Text writer.
        public HtmlTextWriterNoSpan(TextWriter textWriter)
            : base(textWriter)
        { }
    
        /// 
        /// Determines whether the specified markup element will be rendered to the requesting page.
        /// 
        /// Name.
        /// Tag key.
        /// True if the markup element should be rendered, false otherwise.
        protected override bool OnTagRender(string name, HtmlTextWriterTag key)
        {
            // Do not render  tags
            if (key == HtmlTextWriterTag.Span)
                return false;
    
            // Otherwise, call the base class (always true)
            return base.OnTagRender(name, key);
        }
    }
    

    Just FYI, using:

    checkbox.InputAttributes.Add("disabled", "disabled");
    

    has the same effect but:

    1. It's not as convenient as checkbox.Enalbed = false;
    2. The attribute is removed after a postback when the checkbox is in a ListView.

提交回复
热议问题