[英]Dataannotations validation
在 asp.net mvc3 上,我使用數據注釋進行驗證。 我用一個簡單的 if(ModelState.IsValid) 來控制我的 controller 上的驗證。 如何在簡單的 class 而不是 controller 中控制這些驗證?
謝謝!
這幾乎就是 MVC 驗證器在幕后所做的:
這將遍歷所有注釋並確定是否有任何錯誤並將它們添加到錯誤集合中。 最好將它放在基礎 class 中,然后讓所有其他類從它繼承。 如果GetErrors().Any()
返回 true,則 model 無效。
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));
}
錯誤信息 Class:
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): 在 MVC 之外使用 ASP.Net MVC 數據注釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.