對asp.net mvc3我正在使用dataanotations進行驗證。我通過一個簡單的if(ModelState.IsValid)來控制我的控制器上的驗證。我怎樣才能控制這些驗證在一個簡單的類,而不是控制器?Data Annotations驗證
謝謝!
對asp.net mvc3我正在使用dataanotations進行驗證。我通過一個簡單的if(ModelState.IsValid)來控制我的控制器上的驗證。我怎樣才能控制這些驗證在一個簡單的類,而不是控制器?Data Annotations驗證
謝謝!
這是相當多的MVC驗證確實在幕後是什麼:
這將遍歷所有的註釋和我們的身影,如果有任何錯誤,並把它們添加到一個錯誤收集。最好把它放在基類中,然後讓所有其他的類繼承它。如果GetErrors().Any()
返回true,則該模型無效。
public IEnumerable<ErrorInfo> GetErrors() {
return from prop in TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(this))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
}
錯誤信息類:
public class ErrorInfo{
public string Name { get; set; }
public string FormatErrorMessage { get; set; }
public ErrorInfo(string name, string formatErrorMessage){
Name = name;
FormatErrorMessage = formatErrorMessage;
}
}
回答這裏(W/.NET 4): Using ASP.Net MVC Data Annotation outside of MVC