asp.net-mvc – 防止在模型中继承验证属性
我正在使用其他自定义联系模型类继承的基本联系模型.
public class BaseContactModel { [Required(ErrorMessage = "Firstname is required")] public virtual string FirstName { get; set; } } 基本联系人模型使用验证属性来标记属性是必需的,但在某些情况下我想要覆盖或停止它.这有可能吗? public class ContactModel : BaseContactModel { [NotRequired] public override string FirstName { get; set; } } 我尝试使用新的验证属性NotRequired来返回true,但是看起来属性正在堆叠,所以必需& NotRequired正在运行,验证失败. 在寻找解决方案(我找不到)时,我发现一些不相关的属性具有“继承”属性,但我没有在System.ComponentModel.DataAnnotations中的本机验证属性中看到这一点. 这是一个失败的原因吗?我是否需要推出支持禁用继承的自己的版本?任何帮助非常感谢. 解决方法
看到下面这个,我创建了一个继承自另一个BaseModel的类Model,使用new关键字然后验证每个实例中的一个.从我所看到的,他们都使用基本属性.
为了清楚起见,我在验证例程中添加了一个控件类ControlModel. class Program { static void Main(string[] args) { ValidationTest<Model>(); ValidationTest<BaseModel>(); ValidationTest<ControlModel>(); Console.Read(); } private static void WriteAttributeInfo<T>() { Console.WriteLine(string.Concat(typeof(T)," attributes:")); typeof(T).GetProperties().SelectMany(m => m.GetCustomAttributes(true)).Select(a => { Console.WriteLine(a); return a; }).ToList(); } private static void ValidationTest<T>() { object obj = Activator.CreateInstance<T>(); Console.WriteLine(string.Concat(typeof(T)," test: isValid = ",Validator.TryValidateObject(obj,new ValidationContext(obj,serviceProvider: null,items: null),new List<ValidationResult>()))); } } class ControlModel { public string FirstName { get; set; } public string Email { get; set; } } class BaseModel { [RequiredAttribute] public virtual string FirstName { get; set; } [RequiredAttribute] public virtual string Email { get; set; } } class Model : BaseModel { public new string FirstName { get; set; } public new string Email { get; set; } } ConsoleApplication1.Model测试:isValid = False ConsoleApplication1.BaseModel测试:isValid = False ConsoleApplication1.ControlModel测试:isValid = True 从这个示例中,您似乎无法覆盖/隐藏/忽略继承的必需验证(尚未尝试其他人)属性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc-3 – 从Razor _Layout.cshml访问Ses
- entity-framework – 数据读取器与指定的模型不兼
- asp.net – 通过调用.ashx页面下载文件
- 如何使用ASP.NET标识使声明无效?
- 在asp.net中制作某些页面的最佳方法是什么?需要
- VS2005(c#)项目调试问题解决方案集锦 转
- asp.net-mvc – 将存储库注入ASP.NET控制器的最佳
- asp.net-mvc – 在ASP.NET MVC项目和Cordova项目
- 如何在asp.net mvc中使用razor viewmodel将c#gui
- kendo-ui – 如何使用它的ASP MVC Complete Wrap