我正在使用数据注释验证器,如下所示:
http://www.asp.net/learn/mvc/tutorial-39-cs.aspx
Data Annotations Model Binder在codeplex上:
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
我已下载代码,构建代码并引用新的System.ComponentModel.DataAnnotations.dll。我还将默认模型绑定器设置为使用Microsoft.Web.Mvc.DataAnnotations.dll。它绑定到一个简单的对象(例如,Order)时工作正常,但如果我绑定到一个具有CreditCard对象的Order,我在新的绑定器中出错:
对象引用未设置为对象的实例,DataAnnotationsModelBinder.cs行:60。
在我的例子中,fullPropertyKey是“Card”,而modelState是null,所以它显然与Order的Card属性有问题。
ModelState modelState = bindingContext.ModelState[fullPropertyKey];
// Only validate and bind if the property itself has no errors
if (modelState.Errors.Count == 0) {
if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) {
SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
}
}
数据注释绑定器是否支持此功能?库存活页夹对订单没有问题 - > CreditCard结构(当然减去验证)。测试代码:
控制器&型号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.ComponentModel.DataAnnotations;
namespace PAW.Controllers
{
//MODEL
public class Order
{
[Required]
[DataType(DataType.Text)]
[StringLength(5)]
public string CustomerName { get; set; }
public CreditCard Card { get; set; }
public Order()
{
this.Card = new CreditCard();
}
}
public class CreditCard
{
[StringLength(16), Required]
public string Number { get; set; }
}
//CONTROLLER
public class TestController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View(new Order());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Order o)
{
if (ModelState.IsValid)
{
//update
}
return View(o);
}
}
}
观点:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<PAW.Controllers.Order>" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<% using(Html.BeginForm()) { %>
<%=Html.ValidationSummary("Errors: ") %>
<div>
Name (max 5 chars): <%=Html.TextBox("CustomerName", Model.CustomerName)%>
</div>
<div>
CC#: <%=Html.TextBox("Card.Number", Model.Card.Number)%>
</div>
<input type="submit" value="submit" />
<% } %>
</body>
</html>
答案 0 :(得分:0)
这实际上是DataAnnotationModelBinder中的一个错误。但是,假设在即将推出的版本中修复了它。
In this similar question在SO上我在DataAnnotationModelBinder中发布了我的快速修复程序,使其工作,并且是复杂/深度绑定的快速示例。