19

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?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Lücks
  • 3,806
  • 2
  • 40
  • 54

4 Answers4

31

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();
Oleksii Aza
  • 5,368
  • 28
  • 35
  • 1
    see also http://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate – Alexey Oct 14 '14 at 13:06
13

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.");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Nice! But I need to get the Errors, not using ValidationMessageFor. BUt this is a good example – Lücks Jul 10 '13 at 21:25
3

To display all the errors, try:

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

or,

<div class="text-danger">
    @Html.ValidationSummary(false)
</div>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
2

my action code

[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser
        {
            FirstName = registerViewModel.FirstName,
            LastName = registerViewModel.LastName,
            Email = registerViewModel.Email,
            PhoneNumber = registerViewModel.PhoneNumber,
        };
        var result = await userManager.CreateAsync(user, registerViewModel.Password);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", "Home");
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
    }
    return View(registerViewModel);
}

in asp.net core in View write this code

<div class="col-xl-12" style="margin-top:40px;">
    @foreach (var modeleState in ViewData.ModelState.Values)
    {
        foreach (var error in modeleState.Errors)
        {
            <h5 style="color:red;margin-top:8px;">@error.ErrorMessage</h5>
        }
    }
</div>

in asp.net mvc5 in View write this code

@Html.ValidationSummary(false, "", new { @class = "text-danger" })
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Diako Hasani
  • 1,384
  • 13
  • 14