【问题标题】:Possible to change Data Annotations during Runtime? (ASP.NET MVC's [Range] [Required] [StringLength] etc.)可以在运行时更改数据注释吗? (ASP.NET MVC 的 [Range] [Required] [StringLength] 等)
【发布时间】:2011-05-04 13:10:05
【问题描述】:

通常,类成员的 ModelBinding 验证可能会像以下示例一样完成:

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

SomeValue 限制为最多 50 个字符。

是否可以在运行时将常量 (50) 更改为其他值,例如,在该类的每个实例的构造过程中,以便可以有不同的实例具有不同的 StringLength 限制?

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

【问题讨论】:

    标签: asp.net-mvc validation data-annotations model-binding


    【解决方案1】:

    是的。但唯一的方法是创建您自己的 DataAnnotationsModelValidatorProvider 实现,然后在 Global.ascx.cs 中注册它。您不能简单地在运行时删除属性,而是中断读取它们的 MVC 内部:

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

    【讨论】:

    • 嗯...也许,我应该问“有没有简单的方法可以做到这一点?” -- 好的,谢谢回复。我只需要在 Controller 中进行手动验证,因为我只需要检查一个字段。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多