0

I have a MVC4 controller that calls its view multiple times, each time with a different set of ViewBags. The view renders the contents of a Form based on the absence or presence of those ViewBags via something like this:

@using (Html.BeginForm())
{
    @if (ViewBag.Foo1 != null)
    {
        @Html.DropDownList("Bar1",....
    }

    @if (ViewBag.Foo2 != null)
    {
        @Html.DropDownList("Bar2",....
    }

    <input name="ActionButton" type="submit" value="Ok"" />
}

Each time the user clicks the submit button, the controller checks to see what is in the collection and makes a new set of ViewBags before calling the view again, sort of like this:

public ActionResult Create()
{
    ViewBag.Foo1 = "blawblaw";
    return View();
}

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    if (collection["Bar1"] != null)
    {
        string FirstPass = collection["Bar1"];
        ViewBag.Foo2 = "blawblaw";
    }

    if (collection["Bar2"] != null)
    {
        string SecondPass = collection["Bar2"];
        ViewBag.Foo3 = "blawblaw";
    }

    return View();
}

What I need to do now is somehow have each pass thu the controller 'remember' something about its previous passes. That is, in my example, the second pass thru the controller (the one where collection["Bar2"] is true), the value of FirstPass is null.

How can I do that?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
davecove
  • 1,001
  • 4
  • 16
  • 36
  • Sounds like you're trying to recreate a WebForm with MVC, which is not the right way to go. MVC is supposed to be stateless - it doesn't 'remember' anything about what the user has already posted to it unless you are persisting that data somewhere (database). You should look at model binding rather than over-using the viewbag, and also using a different controller. Don't try to force everything through the same url or you might be falling into [this trap](http://37signals.com/svn/posts/2316-so-much-complexity-in-software-comes-from). – Nick Sep 03 '12 at 13:18
  • I get that... but 90% of this app is straight-ahead MVC CRUD functionality and MVC is a good fit there. On this one page however, I need to step the user thru a couple of steps to gather the details I need before making an update to the model. – davecove Sep 03 '12 at 13:33

1 Answers1

0

In that case have a look at best practices for implementing a wizard in MVC. Some good suggestions here. Personally I would still consider using separate and distinct urls. Also, If you have db access in your solution you can still store temporary data before updating the main model. Think about what you want to happen if the user doesn't complete the whole journey the first time round...

Community
  • 1
  • 1
Nick
  • 6,366
  • 5
  • 43
  • 62