通常,类成员的ModelBinding验证可能就像这个例子一样:
public Class someclass { [StringLength(50)] public string SomeValue { get; set; } }
SomeValue最多限制为50个字符.
是否可以在运行时将常量(50)更改为其他内容,例如,在构造该类的每个实例期间,以便可以使用具有不同StringLength限制的不同实例?
如果是这样,那怎么做呢?
解决方法
是.但唯一的方法是创建自己的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() );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。