Add model state error and validate after redirect to action

5.5k views Asked by At

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?

1

There are 1 answers

2
Darin Dimitrov On BEST ANSWER

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