每当我在ASP.NET MVC模型中创建一个布尔属性并尝试使用@Html.CheckBoxFor创建一个复选框时,我就会得到一个自动生成的隐藏表单域。我知道这是有原因的,但每当我提交表单并使用表单集合获取该值时,当它处于选中状态时,它会返回2个值。它像这样提交值- 'true,false‘。现在,当我使用form集合获取值并执行bool.Parse()时,它会抛出一个错误,因为它不能同时解析'true,false‘。有没有办法消除隐藏的表单字段,或者我应该在处理请求时尝试一些东西??
在模型中
[Display(Name ="Is Enabled")]
public bool IsEnabled { get; set; }在控制器中
public ActionResult Request(FormCollection collection)
{
bool valueIsEnabled=bool.Parse(collection["IsEnabled"])
}在视图中
@Html.CheckBoxFor(m => m.IsEnabled, new {
@class = "custom-input"
})当我单击选中时
预期结果- true实际结果- true,false
当我没有单击选中时
预期结果-假实际结果-假
发布于 2019-01-19 17:30:00
好的,我做了一些研究,发现CheckBox帮助器生成了一个与checkbox同名的附加隐藏字段(您可以通过浏览生成的源代码来查看):
<input checked="checked" id="Visible" name="Visible" type="checkbox" value="true" />
<input name="Visible" type="hidden" value="false" />因此,当您提交表单时,这两个值都将发送到控制器操作。下面是直接来自ASP.NET MVC源代码的注释,解释了这个额外的隐藏字段背后的原因:
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.
...https://stackoverflow.com/questions/54265451
复制相似问题