.NET:一般的DataAnnotation属性

ale*_*xey 3 .net c# asp.net asp.net-mvc data-annotations

ASP.NET MVC 2将支持基于DataAnnotation属性的验证,如下所示:

public class User
{
    [Required]
    [StringLength(200)]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何使用纯.NET(不使用MVC绑定,控制器方法等)检查当前模型状态是否有效?

理想情况下,这将是一个单一的方法:

bool IsValid(object model);
Run Code Online (Sandbox Code Playgroud)

sco*_*ttm 7

此代码示例来自Steve Sanderson 关于xVal博客(它使用DataAnnotationsAttribute来验证属性).基本上,你只需要使用反射来枚举attibutes和检查的IsValid() .

internal static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
               from attribute in prop.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}
Run Code Online (Sandbox Code Playgroud)