Get all ModelState errors in view

In my controller, I am adding some ModelState errors. Therefore, when I create my view, I want to get all these errors and change the color of the labels of the fields containing the error.

So, it seems to me, I need to get all ModelState errors, get the field names and then change the color. Is this a good way?

How can I get ModelState errors in my opinion?

+12
source share
3 answers

You can access it through ViewData.ModelState . If you need more control with errors in your view, you can use

ViewData.ModelState.IsValidField("name_of_input")

or get a list of inputs with the following errors:

 var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList(); 
+24
source

In my controller, I am adding some ModelState errors. So, when I look, I want to get all these errors and change the color of the label of the fields containing the error.

This is exactly what will happen if you add a model error with the same key in ModelState as the Html.ValidationMessageFor that you used in your view.

So, suppose, suppose you have the following snippet in your form:

 @Html.LabelFor(x => x.Bazinga) @Html.EditorFor(x => x.Bazinga) @Html.ValidationMessageFor(x => x.Bazinga) 

and in your HttpPost controller action, you can add the following error message to highlight the Bazinga field:

 ModelState.AddModelError("Bazinga", "Please enter a valid value for the Bazinga field"); 

And if you want to add some general error message that is not related to any particular input field, you can always use the @Html.ValidationSummary() at the top of the form to display it. And in the action of your controller:

 ModelState.AddModelError(string.Empty, "Some generic error occurred. Try again."); 
+10
source

To display all errors, try:

 <div asp-validation-summary="All" class="text-danger"></div> 

or

 <div class="text-danger"> @Html.ValidationSummary(false) </div> 
0
source

Source: https://habr.com/ru/post/949164/


All Articles