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

查看:85
本文介绍了如何强制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的新实例,像这样调用验证():

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)错误的情况下,验证将被运行两次。为了避免这种情况,可以将属性添加到您的模型,说一个布尔值验证,一旦它运行,然后手动调用该方法在控制器前检查,你在你的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.

因此​​,在你的控制器:

So 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天全站免登陆