How to remove span tag from WebControl when rendered

后端 未结 15 951
生来不讨喜
生来不讨喜 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:12

    I just had this issue and used Jon's answer, which is good and it works. The downside is that your class is defined within the codebehind and not your markup.

    So I took the answer and made a progamatic way to retrieve all attributes for the control, copy them to InputAttributes and remove those copied attributes from attributes.

    Note that while this extends from RadioButton, you could use the method to extend any control, such as labels or checkboxes.

    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Hidistro.UI.Common.Controls
    {
        /// 
        /// Just like a normal RadioButton, except that the wrapped span is disabled.
        /// 
        public class CleanRadioButton : RadioButton
        {
            protected override void Render(HtmlTextWriter writer)
            {
                List keysToRemove = new List();
    
                foreach (object key in Attributes.Keys)
                {
                    string keyString = (string)key;
                    InputAttributes.Add(keyString, Attributes[keyString]);
                    keysToRemove.Add(keyString);
                }
    
                foreach (string key in keysToRemove)
                    Attributes.Remove(key);
    
                base.Render(writer);
            }
        }
    }
    

    This way, all you need to do is the following, and it will output tags without the span.

    
    
    

    HTML output: (note that "generated" is autogenerated)

    
    
    

提交回复
热议问题