更新时间:2023-02-17 10:26:17
那是因为 CheckBox
助手生成了一个与复选框同名的附加隐藏字段(您可以通过浏览生成的源代码):
That's because the CheckBox
helper generates an additional hidden field with the same name as the checkbox (you can see it by browsing the generated source code):
<input checked="checked" id="Visible" name="Visible" type="checkbox" value="true" />
<input name="Visible" type="hidden" value="false" />
因此,当您提交表单时,两个值都会发送到控制器操作.以下是直接来自 ASP.NET MVC 源代码的注释,解释了此附加隐藏字段背后的原因:
So both values are sent to the controller action when you submit the form. Here's a comment directly from the ASP.NET MVC source code explaining the reasoning behind this additional hidden field:
if (inputType == InputType.CheckBox) {
// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.
...
我建议您使用视图模型作为动作参数或直接使用标量类型,而不是使用 FormCollection
,并将解析的麻烦留给默认模型绑定器:
Instead of using FormCollection
I would recommend you using view models as action parameters or directly scalar types and leave the hassle of parsing to the default model binder:
public ActionResult SomeAction(bool visible)
{
...
}