Possible to change Data Annotations during Runtime? (ASP.NET MVC's [Range] [Required] [StringLength] etc.)

匆匆过客 提交于 2019-12-18 06:26:32

问题


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

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

SomeValue is limited to 50 characters at a maximum.

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?


回答1:


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);
    }
}

Register:

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


来源:https://stackoverflow.com/questions/4088274/possible-to-change-data-annotations-during-runtime-asp-net-mvcs-range-requ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!