ASP.NET MVC 3 数据注释:动态添加验证
我是数据注释的新手。我想知道是否可以(以及如何)动态添加一些验证。解释原因非常广泛,但我有一个在创建时接收和对象的 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为做我想做的事情的最简单方法是实现
IValidatableObject
:另请参阅:类-使用 ASP.NET MVC 3 进行级别模型验证
I think that the simplest way of doing what I wanted is implementing
IValidatableObject
:See also: Class-Level Model Validation with ... ASP.NET MVC 3
自定义属性:
自定义 RequiredIfValidator
注册自定义 DataAnnotationsModelValidatorProvider
在 ViewModel 中使用此 CustomRequiredIf
Custom Attribute:
Custom RequiredIfValidator
Register custom DataAnnotationsModelValidatorProvider
Use this CustomRequiredIf in the ViewModel
这是该博客文章的更新 MVC 3 版本 http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
Heres the updated MVC 3 version of that blog post http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx