asp.net-mvc 从控制器手动设置 ModelState.isValid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3169585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manually Set ModelState.isValid from Controller
提问by Chase Florell
Is there a way for me to manually set the ModelState.isValid = False
from the controller?
有没有办法让我ModelState.isValid = False
从控制器手动设置?
I have some code like this
我有一些这样的代码
Dim _region As Domain.Region = RegionService.GetRegionByNameAndParentID(user.UserRegion, user.ParentRegionID)
If ModelState.IsValid AndAlso Not _region Is Nothing Then
''# ...
Else
Return View(user)
End If
But if _region is nothing, then I don't get any Validation Errors firing.
但是如果 _region 什么都不是,那么我不会触发任何验证错误。
I thought about implementing a custom validator, but it would require hitting the database twice (once for validation and once to set the value).
我考虑过实现自定义验证器,但它需要两次访问数据库(一次用于验证,一次用于设置值)。
回答by richeym
You can't set ModelState.IsValid
directly, as it's a derived property that simply checks the models error collection. You can however add your own model errors, e.g:
您不能ModelState.IsValid
直接设置,因为它是一个派生属性,它只是检查模型错误集合。但是,您可以添加自己的模型错误,例如:
ModelState.AddModelError("Region", "Region is mandatory");
ModelState.IsValid
will then return false.
ModelState.IsValid
然后将返回false。