手动控制器设置ModelState.isValid [英] Manually Set ModelState.isValid from Controller
问题描述
有我手动设置的方式 ModelState.isValid =假
从控制器?
Is there a way for me to manually set the ModelState.isValid = False
from the controller?
我有一些code这样的
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
但如果_region什么的话,我没有得到任何验证错误射击。
But if _region is nothing, then I don't get any Validation Errors firing.
我想过实现自定义的验证,但它需要访问数据库两次(审定一次,一次设置的值)。
I thought about implementing a custom validator, but it would require hitting the database twice (once for validation and once to set the value).
推荐答案
您不能设置 ModelState.IsValid
直接,因为它是一个衍生属性,简单地检查模型错误的集合。但是,您可以添加自己的模型误差,例如:
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.AddModelError("Region", "Region is mandatory");
ModelState.IsValid
然后将返回false。
ModelState.IsValid
will then return false.
这篇关于手动控制器设置ModelState.isValid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!