Linq MVC 2 TryUpdateModel可为null的布尔



我在使用TryUpdateModel更新可为null的布尔值时遇到问题。我创建了一个模板来处理这些值:

<%@ 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数据库类型也被正确定义为可为null的位。

我的代码直截了当:

  var so = new SomeObject();
  if (ModelState.IsValid)
  {
      //gets to here
      if (TryUpdateModel(so))
      {
          //never gets here
      }
   }

该字段上为ModelState报告的错误为:"值'null'对TestField无效。"

这看起来很直接,但我找不到任何关于这方面的信息。如有任何帮助,我们将不胜感激。

干杯,

Brian

由于没有人回答我的问题,我将提出我的解决方法。它不是超级优雅,但它很管用。如果我想让它好看,它应该是粉红色的字体

基本上,我必须使用表单Collection手动加载"so"(someObject),比如so…

var so = new SomeObject();
if (ModelState.IsValid)
{
   so.WasItFound = StringToNullBool(form["WasItFound"]);
   so.WhereWasItFound = form["WhereWasItFound"];
   //fill in the rest of the properties using the form Collection...

}

private bool? StringToNullBool(string s)
{
   if (s != "null")
      return Convert.ToBoolean(s);
   else
      return null;
 }

最新更新