@Html.CheckBoxFor(x => x.IsApproved)
输出:
<input data-val="true" data-val-required="IsApproved 字段是必需的。" id="IsApproved" name="IsApproved" type="checkbox" value="true" />
<input name="IsApproved" type="hidden" value="false" />
它渲染了一个checkbox和一个同名的隐藏input元素。因为浏览器在checkbox未选择时,不会递交checkbox的值。而隐藏值确保了,未选择checkbox时,false会被发送。
在动作方法中查看递交的checkbox值:
string[] s = Request.Form.GetValues("IsApproved");
选择了checkbox时,数组大小为2[true,false],未选择时,数组大小为1[false]。
以下文字来自stackoverflow:
It forces the field to be included if it's unchecked. If you uncheck a check box it doesn't get sent as part of the page - they are only sent if they're checked, and then there's a value of true. The hidden field ensures that false will be send if the check box is unchecked, as the hidden field is always sent.