Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...