.NET:DataAnnotation 属性概述

发布于 2024-08-09 16:00:32 字数 389 浏览 5 评论 0原文

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

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

How can I check that a current model state is valid using only pure .NET (not using MVC Binding 、控制器方法等)?

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

bool IsValid(object model);

ASP.NET MVC 2 will support validation based on DataAnnotation attributes like this:

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

How can I check that a current model state is valid using only pure .NET (not using MVC binding, controller methods, etc.)?

Ideally, it would be a single method:

bool IsValid(object model);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

极度宠爱 2024-08-16 16:00:32

此代码示例来自 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);
    }
}

This code sample is from Steve Sanderson's blog about xVal (which uses the DataAnnotationsAttribute to validate properties). Basically, you just need to enumerate the attibutes using reflection and check 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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文