ModelState.IsValid或Model.IsValid? [英] ModelState.IsValid or Model.IsValid?

查看:116
本文介绍了ModelState.IsValid或Model.IsValid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写它的控制器和单元测试,当我遇到两个方法(同样有效的,我认为),以做一些事情来了。我的所有型号都有一个IsValid属性,我可以检查询问模型,如果是有效还是无效。

I'm writing a controller and unit tests for it, when I came across two ways (equally valid I think) to do something. All my models have an IsValid property, which I can check to ask the model if it's valid or not.

在回发到控制器的操作方法,如果模型是有效的我要救,否则我要重新显示表单用户纠正他们的错误。

On postback to a controller action method, if the model is valid I want to save, otherwise I want to redisplay the form for the user to correct their errors.

我最初的想法是只是验证,如果它是有效的,该模型被问过,但我意识到我也可以查看ModelState.IsValid。

My initial thought was to just verify that the model is being asked if it's valid, but I realized I could also check ModelState.IsValid.

有没有人有什么特别的原因多看一眼VS其他?

Does anyone have any particular reason to look at one vs the other?

推荐答案

我认为有内置到模型的定制业务验证是一个很好的做法。我会处理它的方式将任何自定义验证错误添加到ModelState中:

I think having custom business validation built into your model is a fine approach. The way I would handle it would be to add any custom validation errors to the ModelState:

if (ModelState.IsValid)
{
    if (!model.IsValid)
    {
       ModelState.AddModelError("The model is not valid");
    }
    else
    {
        return RedirectToAction("Index");
    }
}

return View(model);

这样,你的观点有访问验证错误不管他们是否是自定义或内置的。

That way your view has access to the validation errors regardless of whether they are custom or built in.

这篇关于ModelState.IsValid或Model.IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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