Bootply to play with
Visual Studio 2013 generates the following CSHTML when scaffolding an edit view for a model with a boolean:
<div class="form-group">
@Html.LabelFor(model => model.IsUrgent, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsUrgent)
</div>
</div>
</div>
After passing through Razor you get this:
<div class="form-group">
<label class="control-label col-md-2" for="IsUrgent">Is bad :(</label>
<div class="col-md-10">
<div class="checkbox">
<input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" type="checkbox" value="true">
<input name="IsUrgent" type="hidden" value="false">
</div>
</div>
</div>
Twitter Bootstrap 3.2 however doesn't like this way of using labels because this is the result:
Note that the checkbox is positioned too much to the left.
If I wrap my input in a dummy label with some whitespace, ie.
<div class="form-group">
<label class="control-label col-md-2" for="IsUrgent">Is good!</label>
<div class="col-md-10">
<div class="checkbox">
<label><input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" type="checkbox" value="true">
<input name="IsUrgent" type="hidden" value="false"> </label>
</div>
</div>
</div>
I get this:
which looks nice but it's not valid HTML:
The label element may contain at most one input, button, select, textarea, or keygen descendant.
Am I doing something wrong with my CSS classes?
Edit
If I move the second input
outside of the label
as @Saranga suggests I'm still left with the redundant label
that serves no semantic function ...
<div class="checkbox">
<label>
@Html.CheckBoxFor(model => model.IsUrgent)
@Html.DisplayNameFor(model => model.IsUrgent)
</label>
</div>
Instead of @Html.EditorFor(model => model.IsUrgent)
add following code. You can put the hidden field outside the label
tag.
<div class="checkbox">
<label>
<input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" value="true" type="checkbox">
</label>
<input name="IsUrgent" type="hidden" value="false">
</div>
DEMO
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With