3

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

public class User
{
    [Required]
    [StringLength(200)]
    public string Name { get; set; }
}

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

理想情况下,这将是一种方法:

bool IsValid(object model);
4

1 回答 1

7

此代码示例来自 Steve Sanderson关于xVal的博客(它使用 DataAnnotationsAttribute 来验证属性)。基本上,您只需要使用反射枚举属性并检查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);
    }
}
于 2009-10-30T14:56:27.773 回答