2011-05-05 51 views
0

对asp.net mvc3我正在使用dataanotations进行验证。我通过一个简单的if(ModelState.IsValid)来控制我的控制器上的验证。我怎样才能控制这些验证在一个简单的类,而不是控制器?Data Annotations验证

谢谢!

回答

1

这是相当多的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; 

} 
} 
相关问题