Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net checkbox and html data attribute

Tags:

In asp.net, if you use a custom attribute, usually it is rendered as-is.

Considering this markup (note: attributes such as id, name and for were removed in all examples as their generated id/names are verbose):

<asp:TextBox runat="server" data-foo="bar" />

Is rendered in asp.net as:

<input type="text" data-foo="bar" />

That is, asp.net keeps data-foo untouched.

Check box are usually rendered like this:

<asp:CheckBox runat="server" Text="Normal" />

Renders as:

<input type="checkbox" />
<label>Normal</label>

But if you add a custom attribute on a checkbox:

<asp:CheckBox runat="server" Text="Custom attribute" data-foo="bar"  />

It renders as:

<span data-foo="bar">
    <input type="checkbox" />
    <label>Custom attribute</label>
</span>

As you can see, a span in rendered to hold the attribute. This also happens if you add the attribute in code behind. This does not happen with any other HtmlControl, AFAIK.

Does anyone know why this span is rendered to hold the attribute?

Is there anyway to render the attribute in the input tag?

like image 952
Ortiga Avatar asked May 22 '12 17:05

Ortiga


1 Answers

I'm not sure why it's rendered with a span, but I suppose you can add the attribute directly to the input element of the CheckBox in code-behid like this:

myCheckBox.InputAttributes.Add(...)

Reference links:

  • http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.inputattributes.aspx
  • http://forums.asp.net/p/541142/541562.aspx
  • http://msdn.microsoft.com/en-us/library/system.web.ui.attributecollection.add.aspx

Update

An additional parent element is used, so that the attributes you apply to a CheckBox can affect both the input and the text. I suppose it's a span (and not a div), because it's an inline element, making it more convenient to use in different scenarios.

Reference links:

  • http://en.wikipedia.org/wiki/Span_and_div#Differences_and_default_behavior
  • http://learnwebdesignonline.com/span-div
like image 164
Lukasz M Avatar answered Oct 29 '22 03:10

Lukasz M