可能在运行时改变数据注释? (ASP.NET MVC的[范围] [必需] [StringLength]等) [英] Possible to change Data Annotations during Runtime? (ASP.NET MVC's [Range] [Required] [StringLength] etc.)

查看:1250
本文介绍了可能在运行时改变数据注释? (ASP.NET MVC的[范围] [必需] [StringLength]等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常情况下,类成员ModelBinding验证可能像这个例子来完成:

Normally, ModelBinding Validation of a class member might be done like this example:

public Class someclass
{
    [StringLength(50)]
    public string SomeValue { get; set; }
}

someValue中以最大限制为50个字符。

SomeValue is limited to 50 characters at a maximum.

是否有可能具有(50)变更为别的东西在运行时的常数,也就是说,该类的每个实例的施工过程中,因此,它有可能具有不同StringLength局限性变化实例

Is it possible to have the constant (50) changed to something else at run-time, say, during the construction of each instance of that class, so that it is possible to have varying instances with different StringLength limitations?

如果是这样,一个人如何做到这一点?

If so, how does one do this?

推荐答案

是的。但唯一的办法就是创建自己的实施DataAnnotationsModelValidatorProvider,然后在Global.ascx.cs注册。

Yes. But the only way is create your own implementation of the DataAnnotationsModelValidatorProvider and then register it in Global.ascx.cs. You can't simply remove attributes at runtime BUT interupt the MVC internals that read them:

public class ConventionModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        List<Attribute> newAttributes = new List<Attribute>(attributes);
        if( mycondition == true )
        {
            //get rid of the existing attribute
            newAttributes.Remove(newAttributes.OfType<StringLengthAttribute>().First());


            //add a new one 
            newAttributes.Add( new StringLengthAttribute(5324));
        }

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

注册:

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add( new CustomValidatorProvider() );

这篇关于可能在运行时改变数据注释? (ASP.NET MVC的[范围] [必需] [StringLength]等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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