Razor CheckBoxFor helper creates checkboxes that don't seem to work correctly. The helper displays the current Model value just fine, but is always false on form submission - even when checked.
Lots of Google/SO results for this problem and many different workarounds. I found an HTML solution that allows the correct value on form submissions:
<input type="checkbox" id="IsActive" name="IsActive"
value="@(Model.IsActive ? "true" : "false")"
onchange="$(this).val(this.checked)"
@(Model.IsActive ? "checked=checked" : "") />
The above works as-is, but I've been trying to understand how to accomplish the above using the CheckBoxFor helper, but all of my attempts take me right back to where it all started - submitted value is always false, even when checked.
@Html.CheckBoxFor(model => model.IsActive,
new {
@class = "form-check-input",
name = "IsActive",
onchange = "$(this).val(this.checked)",
value = Model.IsActive ? "true" : "false"
}
)
Why does the above HTML checkbox work, but CheckBoxFor is so impossible?
Btw, Model.IsActive is a bool, of course.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…