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