Default CSS3 Checkbox Template in MVC

2019-05-10 13:34发布

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条回答
等我变得足够好
2楼-- · 2019-05-10 14:13

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

查看更多
登录 后发表回答