Asp.net checkbox and html data attribute
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
Just to add another method that I use when all else fails, you can always use a literal control and make it render whatever you want. You need to do a bit more work when handling the postback, but sometimes this is the only way to get the html you need.
Markup:
<asp:Literal ID="myLiteral" runat="server"/>
Codebeside:
myLiteral.Text = string.Format("<input type=\"checkbox\" data-foo=\"{0}\" /><label>Normal</label>", value)
This is the way that render engine builds the CheckBox
control, there isn't very much to do about it.
Something you could do is creating a runat="server"
input.
<input id="myInput" runat="server" type="checkbox" data-foo="bar"/>
<label>Custom attribute</label>
Another option is adding the data-foo
attribute using jquery on document load
$(function(){
$('span[data-foo]').each(function(){
var $span = $(this);
var value = $span.data('foo');
$span.find('input').data('foo',value);
});
})