3

I've been trying to get the default checkbox template written for my Boolean editors and I've run into an issue due to how MVC Razor renders multiple input elements for a single boolean model property.

I have this template defined:

@model Boolean?
<div class="check-box">
    @Html.CheckBox("", Model.HasValue && Model.Value)
    @Html.LabelForWithoutText(m => m, new object())
</div>

If I manually write out the HTML like:

<div class="check-box">
    <input type="checkbox" title="Create?" value="true" name="check" id="chkCreate">
    <label title="Create?" for="chkCreate"></label>
</div>

Everything works fine.

But when Razor renders my template on a Boolean property of a model the html is rather different. Due to how MVC renders other hidden inputs for posting booleans back to action methods.

The Razor version looks like this:

<div class="check-box">
    <input type="checkbox" value="true" name="GloballyShare" id="GloballyShare" data-val-required="The GloballyShare field is required." data-val="true">
    <input type="hidden" value="false" name="GloballyShare">
    <label title="GloballyShare" for="GloballyShare"></label>
</div>

The problem is the extra hidden input. I don't want to change this behaviour as that will globally effect how MVC form work by default and I can't think of a way to deal with this in CSS.

So I'm wondering how this could be achieved. You can see a working example of the problem here:

Default CSS3 Checkbox Template in MVC

If you try it then remove the hidden input element and try it again the top most checkbox starts working the same as the bottom checkbox

1
  • 1
    Liked your solution without relying in images... looks nice! Commented Aug 21, 2013 at 22:38

1 Answer 1

7

I've just managed to fix the jsFiddle.

I changed the label selector from a + to a ~ and both checkboxes are now working:

.check-box input[type=checkbox]:checked + label {

Changed to:

.check-box input[type=checkbox]:checked ~ label {

Fixed jsFiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.