0

I have the following action

[GET("Foo")]
public virtual ActionResult Foo()
{
    return View(new FooViewModel());
}

the view for this action calls this partial view

@{ Html.RenderAction(MVC.FooBar.AddFoo()); }

with controller actions

[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
    var viewModel = new AddFooViewModel();

    return PartialView(viewModel);
}

[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
    // If ModelState is invalid, how do I redirect back to /Foo 
    // with the AddFooViewModel ModelState intact??
    if (!ModelState.IsValid)
        return MVC.FooBar.Foo();

    // ... persist changes and redirect
    return RedirectToAction(MVC.FooBar.Foo());
}

If somebody submits the AddFoo form with ModelState errors, I want the POST action to redirect back to /Foo and show the AddFoo partial view with the ModelState errors. What's the best approach to handle this?

kenwarner
  • 28,650
  • 28
  • 130
  • 173

2 Answers2

0

I think you could achieve that in 2 ways:

  1. Using session state
  2. Passing your data using querystring params

I prefer the second option.

gsimoes
  • 1,011
  • 11
  • 12
0

I ended up putting the viewmodel into TempData like this with the ModelStateToTempData attribute on the controller

[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
    var viewModel = TempData["AddFooViewModel"] as AddFooViewModel ?? new AddFooViewModel();

    return PartialView(viewModel);
}

[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
    // If ModelState is invalid, how do I redirect back to /Foo 
    // with the AddFooViewModel ModelState intact??
    if (!ModelState.IsValid)
    {
        TempData["AddFooViewModel"] = viewModel;
        return RedirectToAction(MVC.FooBar.Foo());
    }

    // ... persist changes and redirect
    return RedirectToAction(MVC.FooBar.Foo());
}
kenwarner
  • 28,650
  • 28
  • 130
  • 173