在MVC中驗證表單資料方法有多種:錯誤匯總顯示,在每個驗證的表單元素後顯示等。www.asp.net/mvc網站上有教程。
(以Northwind的Product表為例,資料和對象使用ADO.NET Entity Data Model自動產生)
當使用一個表單添加一個Models.Product對象到資料庫時,我們在當前Controlle中建立一個Create方法來實現,此方法接受一個Models.Product類型的參數,
在將建立新產品的時候DefaultModelBinder會將表單中的值轉換成Models.Product對象,
DefaultModelBinder方法預設會檢查當前類(在這裡也即是Models.Product)是否繼承IDataErrorInfo介面,當類繼承了IDataErrorInfo介面時,類的每個屬性會調用IDataErrorInfo的的索引器,如果當前索引器返回錯誤,the model binder 會自動將錯誤寫入到model state,Controller類的ModelState中的錯誤在介面中使用Html.ValidationSummary()來顯示。
DefaultModelBinder還會檢測IDataErrorInfo.Error屬性,此屬性工作表示的是與當前類相關的非屬性特性驗證錯誤。
範例程式碼:
Code
public partial class Product:IDataErrorInfo
{
private Dictionary<string, string> _errors = new Dictionary<string, string>();
partial void OnProductNameChanging(string value)
{
if (string.IsNullOrEmpty(value))
_errors.Add("ProductName", "ProductName is required.");
}
IDataErrorInfo 成員#region IDataErrorInfo 成員
public string Error
{
get { return String.Empty; }
}
public string this[string columnName]
{
get
{
if (_errors.ContainsKey(columnName))
{
return _errors[columnName].ToString();
}
else
{
return string.Empty;
}
}
}
#endregion
}