Manually Set ModelState.isValid from Controller

asp.net MvcValidation

asp.net Mvc Problem Overview


Is there a way for me to manually set the ModelState.isValid = False from the controller?

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.

I thought about implementing a custom validator, but it would require hitting the database twice (once for validation and once to set the value).

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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 will then return false.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChase FlorellView Question on Stackoverflow
Solution 1 - asp.net MvcricheymView Answer on Stackoverflow