我在 ASP.NET MVC 表单上使用复选框,如下所示:
<%=Html.CheckBox("AgreeToRules", Model.AgreeToRules)%>
模型上的 AgreeToRules 属性是一个 bool 值。在测试期间,这一切都很好。但是,现在我们已经开始使用这个应用程序,我看到以下消息的错误相对较少但数量很多:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information. ---> System.FormatException: Y is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
当 View 引擎尝试在发布后呈现表单时,似乎会发生这种情况,并且从 ValueProvider 返回的复选框的值如下所示:
Y,false
或者
N,false
以原始形式呈现的 html 如下所示:
<input id="AgreeToRules" name="AgreeToRules" type="checkbox" value="true" />
<input name="AgreeToRules" type="hidden" value="false" />
在测试期间,我期望(并显示)发布的值如下所示:
true,false
如果检查或
false
如果没有检查。那么 N 和 Y 是从哪里来的呢?
我将用户代理添加到从错误处理程序返回的信息列表中,看起来(到目前为止)所有错误都发生在带有 FF 3.0.10 的 Windows XP 下,但这正是我测试过的,问题没有测试过程中存在。
有什么想法吗?
最佳答案
我们在我正在从事的项目(MVC 2)上遇到了同样的问题。我们通过用纯 html 代码替换 helper 来解决它:
前:<%= Html.CheckBox("Credit", false, new {@validate = "required"}) %>
后:
<input type="checkbox" name="Credit" value="true" validate="required" />
<input type="hidden" name="Credit" value="false" />
关于asp.net-mvc - asp.net mvc 复选框不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/936267/