At my Controller I add some ModelState Errors. So, when I render my View, I want to get all these Errors and change the color of the labels of the fields that contain a error.
So, I think I need to get all the ModelState Errors, get the field names and then change the color. This is the a good way?
How can I get the ModelState Errors in my view?
To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.
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.
Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.
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 access it through ViewData.ModelState
.
If you need more control with errors on your view you can use
ViewData.ModelState.IsValidField("name_of_input")
or get a list of inputs with errors like this:
var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList();
At my Controller I add some ModelState Errors. So, when I render my View, I want to get all these Errors and change the color of the labels of the fields that contain a error.
That's exactly what's gonna happen if you add the model error with the exact same key in the ModelState as the Html.ValidationMessageFor helper you used in your view.
So for example let's suppose that in your form you've got the following snippet:
@Html.LabelFor(x => x.Bazinga)
@Html.EditorFor(x => x.Bazinga)
@Html.ValidationMessageFor(x => x.Bazinga)
and in your HttpPost controller action you could add the following error message in order to highlight the Bazinga field:
ModelState.AddModelError("Bazinga", "Please enter a valid value for the Bazinga field");
And if you wanted to add some generic error message which is not associated to some specific input field you could always use the @Html.ValidationSummary()
helper at the top of your form to display it. And in your controller action:
ModelState.AddModelError(string.Empty, "Some generic error occurred. Try again.");
To display all the errors, try:
<div asp-validation-summary="All" class="text-danger"></div>
or,
<div class="text-danger">
@Html.ValidationSummary(false)
</div>
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