ASP.NET MVC 2 将支持基于以下内容的验证 数据标注 像这样的属性:

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

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

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

bool IsValid(object model);
有帮助吗?

解决方案

此代码示例来自 Steve Sanderson 博客 关于 (它使用 DataAnnotationsAttribute 来验证属性)。基本上,您只需要使用反射枚举属性并检查 已验证():.

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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top