复选框不适用于布尔视图模型属性 [英] Checkbox not working with boolean viewmodel property
问题描述
我正在使用MVC6,并且我的表单中有一个复选框输入字段,但是提交表单时,复选框的值总是以false的形式传递给ViewModel:
I am using MVC6 and have a checkbox input field in my form, but when the form is submitted the value for the checkbox always gets passed to the ViewModel as false:
以下是在我的ViewModel中声明属性的方式:
[Display(Name = "Include Sales Tax")]
public bool IncludeSalesTax { get; set; }
以下是该表单在我的MVC6剃须刀表单中的外观:
<div class="form-group">
<div class="checkbox">
<label><input asp-for="IncludeSalesTax" type="checkbox" value="">@Html.DisplayNameFor(m => m.IncludeSalesTax)</label>
</div>
</div>
我认为以上是遵循Twitter Bootstrap标准并使用ASP.NET MVC6 asp-for标签进行模型绑定的最佳方法.
I figured the above would be the best way to follow Twitter Bootstrap standards and use the ASP.NET MVC6 asp-for tag for model binding.
当我提交表单时,即使已选中,IncludeSalesTax的值也始终为false.我在做什么错了?
When I submit the form the value for IncludeSalesTax is always false, even when checked. What am I doing wrong?
推荐答案
在让Visual Studio根据我的ViewModel生成表单之后,下面是它的操作方法:
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>
这篇关于复选框不适用于布尔视图模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!