Jal*_*lal 25 c# checkbox asp.net-mvc-2
我正在使用Html.Checkbox("Visible")向用户显示一个复选框.在回发中,FormCollection["Visible"]值是"真,假".为什么?
在视图中:
<td>
<%: Html.CheckBox("Visible") %>
</td>
Run Code Online (Sandbox Code Playgroud)
在控制器中:
adslService.Visible = bool.Parse(collection["Visible"]);
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 30
这是因为CheckBox帮助程序生成一个与复选框同名的附加隐藏字段(您可以通过浏览生成的源代码来查看它):
<input checked="checked" id="Visible" name="Visible" type="checkbox" value="true" />
<input name="Visible" type="hidden" value="false" />
Run Code Online (Sandbox Code Playgroud)
因此,当您提交表单时,这两个值都将发送到控制器操作.这是一个直接来自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.
...
Run Code Online (Sandbox Code Playgroud)
而不是使用FormCollection我会建议您使用视图模型作为操作参数或直接标量类型,并将解析的麻烦留给默认模型绑定器:
public ActionResult SomeAction(bool visible)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我最近处理了这个问题,并提出了一种绕过MVC绑定并在查询字符串上使用Contains("true")的方法.没有其他任何对我有用.
如果人们坚持其他答案,那么这对我有用 - http://websitesorcery.com/post/2012/03/19/CheckBox-Issue-with-MVC-3-WebGrid-Paging-Sorting.aspx
| 归档时间: |
|
| 查看次数: |
26592 次 |
| 最近记录: |