Checkbox not working with boolean viewmodel property

强颜欢笑 提交于 2019-12-03 23:34:35

input type checkbox sends an "on" if it is set. Otherwise it is not sent. It is important, that you set the value attribute to true. In this case it sends true or nothing, which is perfect to bind to a boolean.

<input type="checkbox" name="yourPropertyName" value="true" checked />

The razor view engine normally creates a checkbox and one hidden input using the same name.

You can simply use the html below to ensure you get your desired result:

<div class="form-group">
        <div class="checkbox">     
    <input type="checkbox" value="true" name="IncludeSalesTax" />Include Sales Tax
    <input type="hidden" value="false" name="IncludeSalesTax" />
        </div>
    </div> 

After letting Visual Studio generate the form based on my ViewModel here is how it does it:

        <div class="checkbox">
            <input asp-for="isTaxable" />
            <label asp-for="isTaxable"></label>
        </div>

Additionally, I was missing the closing of my input tag. So it can also be done like this which is the bootstrap preferred way:

<label><input asp-for="isTaxable" type="checkbox" value=""/>@Html.DisplayNameFor(m => m.isTaxable)</label>
user3408322

Pinki's answer above is good if the checkbox should default to checked.

If the checkbox should default to unchecked, a little in-line javascript sets the value to true or false upon clicking:

<input name="yourPropertyName" type="checkbox" value="false" onchange="this.value=this.checked">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!