DataAnnotations动态属性附加 [英] DataAnnotations dynamically attaching attributes

查看:189
本文介绍了DataAnnotations动态属性附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,这是可能的动态附加DataAnnotation属性在运行,因此实现动态验证对象属性

Apparently it is possible to dynamically attach DataAnnotation attributes to object properties at runtime and as such achieve dynamic validation.

有人可以提供这方面的code样?

Can someone provide code sample on this?

推荐答案

MVC有一个挂钩提供自己的ModelValidatorProvider。默认的MVC 2使用一个子类ModelValidatorProvider称为DataAnnotationsModelValidatorProvider即能用于验证System.DataAnnotations.ComponentModel.ValidationAttribute属性

MVC has a hook to provide your own ModelValidatorProvider. By default MVC 2 uses a sub class of ModelValidatorProvider called DataAnnotationsModelValidatorProvider that is able to use System.DataAnnotations.ComponentModel.ValidationAttribute attributes for validation.

该DataAnnotationsModelValidatorProvider使用反射来找到所有的ValidationAttributes,只是遍历集合,以验证您的模型。所有你需要做的是覆盖一个方法叫做GetValidators和你选择哪个源注入自己的属性。我用这个方法做的约定验证,性能与DataType.Email属性总是被通过正则表达式过去了,使用此技术从数据库中提取信息,以实施更严格的验证为非电的用户。

The DataAnnotationsModelValidatorProvider uses reflection to find all the ValidationAttributes and simply loops through the collection to validate your models. All you need to do is override a method called GetValidators and inject your own attributes from whichever source you choose. I use this technique to do convention validations, the properties with DataType.Email attribute always gets passed through a regex, and use this technique to pull information from the database to apply more restrictive validations for "non-power" users.

下面的例子只是说永远做任何名字的属性要求的

The following example simply says "always make any FirstName properties required":

 public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
 {
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        //go to db if you want
        //var repository = ((MyBaseController) context.Controller).RepositorySomething;

        //find user if you need it
        var user = context.HttpContext.User;

        if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "FirstName")
            attributes = new List<Attribute>() {new RequiredAttribute()};

        return base.GetValidators(metadata, context, attributes);
    }
}

所有你需要做的就是在你的Global.asax.cs文件中注册供应商:

All you have to do is register the provider in your Global.asax.cs file:

    protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
    }

最终结果是:

有这位模特:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
}

这篇关于DataAnnotations动态属性附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆