Get all ModelState Errors on view

2019-06-15 13:38发布

问题:

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?

回答1:

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();


回答2:

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.");