So I am having some trouble accessing my model errors within my Razor view.
In my controller, when either the ModelState is not valid or some other custom validation does not pass, I add model errors like this: ModelState.AddModelError("ModelState", "Please fill out all required fields.");
Then I return a redirect like so:
return RedirectToAction("Register", "Account");
Seems fairly simple, however, when I try and access the model state errors, loop through them, and add them each as a separate span to my view, I get nothing at all displayed. Here’s the code in the view:
@foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
{
<span>@error.ErrorMessage</span>
<br />
}
Am I doing something wrong here, or not doing something I should be?
You should not redirect to action, just return same view:
Updated: ModelState.IsValid – mistyped 🙂