How to create an EditorTemplate for bootstrap checkbox?

∥☆過路亽.° 提交于 2019-11-28 02:03:38

The CheckBoxFor() method generate 2 inputs to ensure a value is posted back (unchecked checkboxes to not submit a value so the hidden input ensures false is submitted), and you should not attempt to change this behavior. Your attempt at an EditorTempate could not work for a number of reasons including a checkbox (which has 2 states) cannot bind to a nullable bool (which has 3 states) and your else block means that a vale of false will always be submitted, even if the checkbox is checked.

Instead, use the CheckBoxFor() method, but adjust your css selectors

<div class="checkbox">
    <label>
        @Html.CheckBoxFor(m => m.IsActive, new { @class = "checkbox style-1" })
        <span>Checkbox 1</span>
    </label>
</div>

will generate

<div class="checkbox">
    <label>
        <input type="checkbox" name="IsActive" class="checkbox style-1" ... value="true">
        <input type="hidden" name="IsActive" value="false">
        <span>Checkbox 1</span>
    </label>
</div>

So your current selector

label input[type=checkbox].checkbox + span:before {

which gets the span element placed immediately after the checkbox element needs to be changed to

label input[type=checkbox].checkbox ~ span:before {

And ditto for the other selectors (i.e. change + to ~). The ~ selector matches the second element if it is preceded by the first, and both share a common parent (refer General sibling selectors)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!