views:

40

answers:

1

I'm simply trying to pass the ModelState from one action to another in the same controller, for validation purposes. However, the model state does not get updated. I see that TempData["__MvcContrib_ValidationFailures__"] contains the ModelStateDictionary from the forwarding Action, but I assumed this should get transfered into my current ModelState automatically? Where am I going wrong?

I'm using ASP.NET MVC2 and MVCContrib 2.0.36.0. I have also tried decorating the Controller with this attribute, but the results are the same.

Code:

[HttpGet]
[ModelStateToTempData]
public ActionResult NewsEventsSignup()
{
    var newsEventsSignupDetails = this.TempData.GetItem<NewsEventsSignupDetails>();

    var viewModel = _newsEventsSignupPageViewModelMapper.MapFrom(newsEventsSignupDetails);

    return this.View(viewModel);
}

[HttpPost]
[ModelStateToTempData]
[ValidateAntiForgeryToken]
public ActionResult NewsEventsSignup(NewsEventsSignupFormViewModel newsEventsSignup)
{
    ActionResult resultToReturn;

    var newsEventsSignupDetails = _newsEventsSignupDetailsMapper.MapFrom(newsEventsSignup);

    try
    {
        _newsEventsSignupTasks.SignupForNewsAndEvents(newsEventsSignupDetails);
        resultToReturn = this.RedirectToAction(x => x.Index());
    }
    catch (RulesException e)
    {
        e.AddModelStateErrors(this.ModelState); // from xVal
        this.TempData.AddItem(newsEventsSignupDetails); // for showing invalid input
        resultToReturn = this.RedirectToAction(x => x.NewsEventsSignup());
    }

    return resultToReturn;
}
+1  A: 

How do you check that ModelState is not filled? This is an OnActionExecuted filter, so it is only filled, when the Action finished. You can not check the value in the action.

The easiest way to validate that an ModelState realy has an error is to put a validation summary on the view.

To see that your error is not xval related I would try

ModelState.AddModelError("TestError", "This is an errortest");

In NewsEventsSignup before redirecting.

Also dont try to acces TempData in the debugger or in some debug-code. It is deleted the first time you access it.

Malcolm Frexner
I didn't know it was an OnActionExecuted filter. The validation summary brought the truth to light. I'm not getting the input or field validation error classes set because my errors are on ".Name" and ".Email" rather than "Name" and "Email" which is what the names/ids of the input fields are. Strange. Not sure why the . is getting inserted. Otherwise, things seem to be working.
Chris F
Just ran across this issue myself, thanks Malcolm and Chris F for posting the question!
JoseMarmolejos