我使用的數據註釋驗證,這裏概述:是否有可能在asp.net mvc中使用「複雜」模型和Data Annotation Model Binder?
http://www.asp.net/learn/mvc/tutorial-39-cs.aspx
的數據註釋模型綁定是在CodePlex上:
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
我已經下載了代碼,建造它,並引用了新的System.ComponentModel.DataAnnotations.dll。我還設置了默認模型聯編程序以使用Microsoft.Web.Mvc.DataAnnotations.dll。它綁定到一個簡單的對象(例如,訂單)時工作正常,但如果綁定到具有CreditCard對象的訂單,則在新綁定程序中出現錯誤:
未將對象引用設置爲對象,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>
謝謝。我實施了修復。我一直在想,它認爲它必須是一個比空檢查更大的東西..猜我錯了。 :-) – ericvg 2009-09-22 17:19:30