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).
ModelState. AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .
You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.
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.
Mvc Controller. Model State Property System. Web. Mvc Gets the model state dictionary object that contains the state of the model and of model-binding validation. The model state dictionary.
Model binding and model validation occur before executing a controller action in our APIs. Moreover, the ModelState object has an IsValid property where we can check its state. This property is exposed since it should be an application’s responsibility to review ModelState and act accordingly.
Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field. Model validation occurs after model binding and reports errors where data doesn't conform to business rules.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With