如何强制 MVC 验证 IValidatableObject [英] How to force MVC to Validate IValidatableObject

查看:25
本文介绍了如何强制 MVC 验证 IValidatableObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎当 MVC 验证它首先通过 DataAnnotation 属性(如必需或范围)运行的模型时,如果其中任何一个失败,它会跳过在我的 IValidatableObject 模型上运行 Validate 方法.

It seems that when MVC validates a Model that it runs through the DataAnnotation attributes (like required, or range) first and if any of those fail it skips running the Validate method on my IValidatableObject model.

即使其他验证失败,有没有办法让 MVC 继续运行该方法?

Is there a way to have MVC go ahead and run that method even if the other validation fails?

推荐答案

您可以通过传入一个新的 ValidationContext 实例来手动调用 Validate(),如下所示:

You can manually call Validate() by passing in a new instance of ValidationContext, like so:

[HttpPost]
public ActionResult Create(Model model) {
    if (!ModelState.IsValid) {
        var errors = model.Validate(new ValidationContext(model, null, null));
        foreach (var error in errors)                                 
            foreach (var memberName in error.MemberNames)
                ModelState.AddModelError(memberName, error.ErrorMessage);

        return View(post);
    }
}

这种方法的一个警告是,在没有属性级 (DataAnnotation) 错误的情况下,验证将运行两次.为避免这种情况,您可以向模型添加一个属性,例如一个布尔值 Validated,一旦它运行,您就在 Validate() 方法中将其设置为 true,然后在手动调用控制器中的方法之前进行检查.

A caveat of this approach is that in instances where there are no property-level (DataAnnotation) errors, the validation will be run twice. To avoid that, you could add a property to your model, say a boolean Validated, which you set to true in your Validate() method once it runs and then check before manually calling the method in your controller.

所以在你的控制器中:

if (!ModelState.IsValid) {
    if (!model.Validated) {
        var validationResults = model.Validate(new ValidationContext(model, null, null));
        foreach (var error in validationResults)
            foreach (var memberName in error.MemberNames)
                ModelState.AddModelError(memberName, error.ErrorMessage);
    }

    return View(post);
}

在您的模型中:

public bool Validated { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
    // perform validation

    Validated = true;
}

这篇关于如何强制 MVC 验证 IValidatableObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆