ASP.NET MVC 3数据注释:动态添加验证
发布时间:2020-12-15 23:37:59 所属栏目:asp.Net 来源:网络整理
导读:我是新的数据注释.我想知道是否可能(以及如何)动态添加一些验证.解释为什么是非常广泛的,但是我有一个ViewModel在创建时接收和对象.在该对象中,我必须检查一些属性,并根据其值应该有或没有一些验证. 一个例子: public class ProfileViewModel{ [Required(Er
我是新的数据注释.我想知道是否可能(以及如何)动态添加一些验证.解释为什么是非常广泛的,但是我有一个ViewModel在创建时接收和对象.在该对象中,我必须检查一些属性,并根据其值应该有或没有一些验证.
一个例子: public class ProfileViewModel { [Required(ErrorMessage = "The field {0} is required")] [Display(Name = "Client Code")] public int ClientCode { get; set; } [Required(ErrorMessage = "The field {0} is required")] [StringLength(100,ErrorMessage = "The field {0} must have up to 100 characters.")] [Display(Name = "Company")] public string Company { get; set; } [StringLength(50,ErrorMessage = "The field {0} must have up to 50 characters.")] [Display(Name = "Name")] public string Name { get; set; } [StringLength(50,ErrorMessage = "The field {0} must have up to 50 characters.")] [Display(Name = "LastName")] public string LastName { get; set; } public ProfileViewModel(User usr) { if (usuario.ClientCode != null) { ClientCode = Convert.ToInt32(usr.ClientCode); } else { //ClientCode and Company are not yet required. //Name and LastName are now required. } Company = usr.Company; Name = usr.Name; LastName = usr.LastName; } } 解决方法
我认为最简单的做法就是实现
IValidatableObject :
public class Product : IValidatableObject { public int Prop1 { get; set; } public int Prop2 { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Prop1 < Prop2) yield return new ValidationResult("Property 1 can't be less than Property 2"); } } 参见:Class-Level Model Validation with … ASP.NET MVC 3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 开发的理想开发/测试/ QA环境
- asp.net-mvc – 如何从ASP.NET MVC Controller Action流式传
- 更新映像而不会闪烁ASP.NET C#
- asp.net-mvc-3 – OutputCache属性和jQuery Ajax没有缓存
- asp.net – 如何在调用Crystal Reports ExportToHttpRespon
- asp.net-web-api – 在MVC 6中不可用的ResponseType
- jquery form表单提交插件asp.net后台中文解码
- iis-7 – ASP经典IIS7问题
- ASP.NET中MVC使用AJAX调用JsonResult方法并返回自定义错误信
- asp.net-web-api – 设计REST ful ODATA API,结果集为空时如
推荐文章
站长推荐
热点阅读