1

I have a question about ModelState and validation error messages in MVC3. I have in my register view the @Html.ValidationSummary(false) that shows me the DataAnnotations error messages from my Model object. Then.. in my Register action controller i have the ModelState.IsValid, but inside that if(ModelState.IsValid) i have another error controls that add to the modelstate with ModelState.AddModelError(string.Empty, "error...") and then I do a RedirectToAction, but the messages added in the ModelState doesn't show at all.

Why this is happening?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Phoenix_uy
  • 3,173
  • 9
  • 53
  • 100

1 Answers1

5

and then i do a RedirectToAction

That's your problem. When you redirect the model state values are lost. Values added to the modelstate (including error messages) survive only for the lifetime of the current request. If you redirect it's a new request, therefore modelstate is lost. The usual flow of a POST action is the following:

[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        // there were some validation errors => we redisplay the view
        // in order to show the errors to the user so that he can fix them
        return View(model);
    }

    // at this stage the model is valid => we can process it 
    // and redirect to a success action
    return RedirectToAction("Success");
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Mmm... so.. i need to do a return View()?.. but the view is in another controller.. (yes, i know, maybe this is wrong.. but at this point i think i dont have the time to change it :S) – Phoenix_uy Dec 30 '11 at 18:59
  • @Phoenix_uy For a "quick" fix add the view to the shared directory as it is there specifically to share Views across multiple controllers. – Jesse Dec 30 '11 at 19:24