ModelState.IsValid 还是 Model.IsValid? [英] ModelState.IsValid or Model.IsValid?

查看:23
本文介绍了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.

有没有人有什么特别的理由来比较两者?

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