如何为视图模型添加自定义验证方法
我尝试为 ViewModel 类添加自定义验证器:
[Serializable]
public class UserViewModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
yield return new ValidationResult("Fail this validation");
}
}
不幸的是,调用 Action 方法时不会触发此操作,例如
[HttpPost]
public ActionResult Edit(UserViewModel user)
如何添加自定义验证逻辑? ValidationAttribute 没有提供足够简单的解决方案。我无法找到有关 MVC2 验证机制的明确信息。
I tried to add custom validator for ViewModel class:
[Serializable]
public class UserViewModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
yield return new ValidationResult("Fail this validation");
}
}
Unfortunately this is not triggered when Action method gets called, e.g.
[HttpPost]
public ActionResult Edit(UserViewModel user)
How can I add custom validation logic? ValidationAttribute does not provide easy enough solution. I am unable to find clear information on MVC2 validation mechanisms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ASP.NET 2.0 不支持 IValidatableObject 。 ASP.NET MVC 3 中添加了对此接口的支持。您可以定义自定义属性:
,然后使用此属性装饰您的视图模型:
IValidatableObject is not supported in ASP.NET 2.0. Support for this interface was added in ASP.NET MVC 3. You could define a custom attribute:
and then decorate your view model with this attribute:
你的语法看起来是正确的。在您尝试验证模型之前,不会“触发”验证。你的控制器代码应该是这样的
Your syntax looks right. The validation isn't "triggered" until you try to validate your model. Your controller code should look like this