Linq MVC 2 TryUpdateModel 可空布尔值
我在使用 TryUpdateModel 更新可为 null 的 bool 值时遇到问题。我创建了一个模板来处理这些值,如下所示:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Boolean?>" %>
<% if (ViewData.ModelMetadata.IsNullableValueType) { %>
<%= Html.DropDownListFor(model => model, new SelectListItem[] { new SelectListItem() { Text = "", Value = "null"},new SelectListItem() { Text = "Yes", Value = "true"}, new SelectListItem() { Text = "No", Value = "false" }})%>
<% } else { %>
<%= Html.CheckBoxFor(model => model.Value)%>
<% } %>
我的视图如下所示:
<%=Html.EditorFor(model => model.TestField) %> //which looks/acts correctly
SQL Server 数据库类型也被正确定义为可为空位。
我的代码很简单:
var so = new SomeObject();
if (ModelState.IsValid)
{
//gets to here
if (TryUpdateModel(so))
{
//never gets here
}
}
该字段上的 ModelState 报告的错误是:“值‘null’对于 TestField 无效。”
这看起来很简单,但我找不到任何相关内容。任何帮助将不胜感激。
干杯,
布莱恩
I have been having an issue with updating a nullable bool value using TryUpdateModel. I have a template created to handle the values as so:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Boolean?>" %>
<% if (ViewData.ModelMetadata.IsNullableValueType) { %>
<%= Html.DropDownListFor(model => model, new SelectListItem[] { new SelectListItem() { Text = "", Value = "null"},new SelectListItem() { Text = "Yes", Value = "true"}, new SelectListItem() { Text = "No", Value = "false" }})%>
<% } else { %>
<%= Html.CheckBoxFor(model => model.Value)%>
<% } %>
My View looks like this:
<%=Html.EditorFor(model => model.TestField) %> //which looks/acts correctly
The SQL Server Database types are also defined correctly as a nullable bit.
My Code is straight forward:
var so = new SomeObject();
if (ModelState.IsValid)
{
//gets to here
if (TryUpdateModel(so))
{
//never gets here
}
}
The Error reported for ModelState on that field is: "The value 'null' is not valid for TestField."
This seems pretty straight forward, but I wasn't able to find anything on this. Any help would be greatly appreciated.
Cheers,
Brian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于没有人回答我的问题,我将提出我的解决方法。它不是超级优雅,但很有效。如果我想让它漂亮的话,它会是粉红色的字体。 ;)
基本上我必须使用表单 Collection 手动加载“so”(someObject),如下所示......
Since nobody has answered my question, I will put my workaround up. It's not super elegant, but it works. If I wanted it to be pretty, it'd be in a pink font. ;)
Basically I had to load "so" (someObject) manually using the form Collection like so...