62

I would expect this:

<asp:CheckBox    ID="CheckBox1"    runat="server" CssClass="myClass" />
<asp:RadioButton ID="RadioButton1" runat="server" CssClass="myClass" />
<asp:TextBox     ID="TextBox1"     runat="server" CssClass="myClass" />

...to render like this (with some attributes removed for simplicity):

<input id="CheckBox1"    type="checkbox" class="myClass" />
<input id="RadioButton1" type="radio"    class="myClass" />
<input id="TextBox1"     type="text"     class="myClass" /> 

...when in fact, the RadioButton and CheckBox get wrapped with a span tag and the CSS class gets applied there.

<span class="myClass"><input id="CheckBox1"    type="checkbox" /></span> 
<span class="myClass"><input id="RadioButton1" type="radio"    /></span> 
<input type="text" id="TextBox1" class="myClass" /> 

Is there a reason for this and is there a way to avoid it? It makes jQuery selectors ugly since you can't catch all of them with:

$("input.myClass")

Granted it is just going to:

$("input.myClass, span.myClass input")

...but that is ugly. I could write my own selector, but again not as elegant as it should be.

5
  • 2
    Not an answer, but just commiserating - when I first started working on the .NET platform a few years back and was using JS to find out the value of a checkbox, I spent a few hours trying to figure out why my values were not alerting. Guess what - the span tags. I've always wondered why MS added redundant tags for their radiobuttons and checkboxes!
    – DLS
    Jun 15, 2009 at 17:38
  • @Hardwareguy Sometimes that will be the span and sometimes that will be the input. That is the problem. $("input.myclass") might be a little over-specific, but $(".myClass") would give you the same headache.
    – Mark
    Jun 15, 2009 at 18:50
  • 1
    If you use the Checkbox.Text property, a label is added. The span will then surround them both, and the styles applies to both. That's the reason for the surrounding span.
    – magnattic
    Jun 18, 2012 at 14:42
  • Probably because of things like this: stackoverflow.com/questions/7398462/…
    – Patrick
    Mar 5, 2015 at 20:03
  • For the asp:checkbox i noticed that the span is also added when you use the CssClass property. Sep 27, 2016 at 11:26

7 Answers 7

135

This was driving me crazy too until I found the inputAttributes property.

For example, here is how to add a class directly on the checkbox control without the span nonsense:

myCheckBoxControl.InputAttributes.Add("class", "myCheckBoxClass")
7
  • 9
    If I could, I would give +100, as I am unable to I am giving a +1 :) Thanks!
    – k25
    May 22, 2012 at 14:29
  • 7
    Great job finding this. Also note that LabelAttributes works accordingly to style the corresponding Checkbox label.
    – magnattic
    Jun 18, 2012 at 14:29
  • it strange because myCheckBoxControl.Attributes.Add will trigger the same behavior as myCheckBoxControl.CssClass where it wraps it in a <span> tag, but myCheckBoxControl.InputAttributes.Add will not - yay!
    – Chris Barr
    Nov 8, 2013 at 17:33
  • 1
    Unfortunately, classes added using this method don't get captured in viewstate, whereas classes added using CssClass DO get captured in viewstate.
    – csj
    Feb 25, 2015 at 21:09
  • where to add this. I am unable to get InputAttributes in code behind c# Feb 4, 2017 at 0:33
53

Web controls in the System.Web.UI.WebControls namespace may render differently in different browsers. You can't count on them rendering the same elements always. They may add anything that they think is needed to make it work in the specific browser.

If you want to have any control over how the controls are rendered as html, you should use the controls in the System.Web.UI.HtmlControls namespace instead. That is:

<input type="checkbox" id="CheckBox1" runat="server" class="myClass" />
<input type="radio" name="RadioButton1" runat="server" class="myClass" />
<input type="text" id="TextBox1" runat="server" class="myClass" />

They will render just as the corresponding html element, with no extra elements added. This of course means that you will have to take responsibility for the browser compatibility, as the control doesn't. Also, those controls doesn't have all the features of the controls in the WebControls namespace.

3
  • With how many postbacks happen I think this would be more of a headache. I agree that we should be using these controls by default and stepping up to the WebControls when needed.
    – Mark
    Jun 15, 2009 at 19:01
  • 15
    If you're going to do this, you might as well just use ASP.Net MVC ;)
    – womp
    Jun 15, 2009 at 19:15
  • 5
    @womp I would love that to be an option.
    – Mark
    Jun 15, 2009 at 19:42
5

Every WebControl by default renders as a <span> tag, plus any custom rendering that the control author adds.

One of the first things you usually do when you write a custom WebControl is to override the "TagKey" property to render a div, or something besides a span. The default value of this property is HtmlTextWriterTag.Span.

You could subclass your checkbox items and override the TagKey property to render something else, but then you have to deal with making all your checkboxes into your own version.

1
  • I guess you have to pick your poison. Ugly jQuery selectors or sporadic subclassed controls for consistent rendering. I would be cool if all input controls rendered with a span. Consistency is a half-way decent thing.
    – Mark
    Jun 15, 2009 at 18:59
3

I came across this issue and am attempted to solve it using control adaptors.

See here for an example of doing this to a radio button list.

I ended up with this as my RadioButtonAdaptor-

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;

public class RadioButtonAdapter : WebControlAdapter
{
    protected override void Render(HtmlTextWriter writer)
    {
        RadioButton targetControl = this.Control as RadioButton;

        if (targetControl == null)
        {
            base.Render(writer);

            return;
        }

        writer.WriteBeginTag("input");
        writer.WriteAttribute("type", "radio");
        writer.WriteAttribute("name", targetControl.GroupName);
        writer.WriteAttribute("id", targetControl.ClientID);            

        if (targetControl.CssClass.Length > 0)
        {
            writer.WriteAttribute("class", targetControl.CssClass);
        }      

        writer.Write(" />");

    }
}

And this added to my browsers file-

<browser refID="Default">
        <controlAdapters>            
            <adapter controlType="System.Web.UI.WebControls.RadioButton"
               adapterType="RadioButtonAdapter" />
        </controlAdapters>
</browser>

Of course, there are some downsides to this. Along with those mentioned at the above link, you also lose functionality if you do not impliment everything (the above code does not allow for a radio button to be checked). There are some CSS friendly control adaptors, but they do not cover the radio button control. It may be possible to use Reflector to get the default control adaptor as a starting point.

1
  • I like this suggestion! Late comment I know, but this helped me a lot today! Jan 6, 2011 at 13:52
3

The plain RadioButton is often rendered without a span. If you set CssClass, Style, Enabled properties, the RadioButton is rendered with a span. This inconsistency is a real pain when I need to manipulate the radio button with client-side scripts. What I usually do is to apply a dummy CssClass so that it will always render a span consistently.

1

the best way i think is this:


    public class HtmlTextWriterNoSpan : HtmlTextWriter
    {
        public HtmlTextWriterNoSpan(TextWriter textWriter) : base(textWriter)
        { 
        }

        protected override bool OnTagRender(string name, HtmlTextWriterTag key)
        {
            if (name == HtmlTextWriterTag.Span)
            {
                return false;
            }

            return base.OnTagRender(name, key);
        }
    }

to use it in custom control:


    protected override void Render(HtmlTextWriter writer)
    {
        writer = new HtmlTextWriterNoSpan(writer);
        base.Render(writer);
        // HERE MORE CODE
    }

1
0

Found similar issue, wrote a simple jQuery based function to enable/disable checkbox and parent span

function resetChk(ctl, bEnable) { 

            if (bEnable){
                ctl.removeAttr('disabled').parent().removeAttr('disabled');
            }else{
                ctl.attr('disabled', true).parent().attr('disabled', true);
            }

        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.