20
votes

I'd like to construct an object in different steps in an asp.net mvc application, each step being a different page. The sort of thing you'd store in Session in a quick Web.Forms application.

Reading about it, Session doesn't seem to me as something very asp.net MVC'ish. However I can't really think of other alternatives to this situation as TempData and ViewData don't seem to fit either, so maybe I'm wrong.

Of course I could put the 4 steps in one page and show/hide, but that's not my point with the question. I'd like to hear your opinion about Session in MVC, if it's a good aproach for this kind of multi-step problem or you tend to do it in other ways.

This is very much like question Session variables in ASP.NET MVC, except that I'm not looking for how to access Session, but if it's the best way to solve such a problem or there is something better I'm missing in Asp.Net MVC.

Thanks in advance

3

3 Answers

19
votes

There is nothing un-MVC about Session, its a vital part of the web and most sites use it in some way. You really have two main options. Either store the object in the database between pages (which means saving an incomplete object) or put it in session. Both have advantages and disadvantages.

In session you don't have to save a partial object to the database, but if the user leaves or the session times out you lose all that information. It can also lead to a larger memory footprint per user and when you get to scaling it causes some other problems. (all of which can be solved using sticky-session on a load balancer or central session store).

The database way is better in lots of ways but usually you don't want to save incomplete object to the database, one compromise is to create another table and to save the object serialized to that table. Its not going through your real tables and so you don't have to compromise on your database constraints. (you can also store session data in the database which is basically doing the same thing)

In the end its a judgment call between the two ways, I have used both over the years.

2
votes

You can pass it between Views with TempData... but you have to maintain passing it through subsequent views. It is meant to be consumed by subsequent request, but thats not to say you couldnt pass temp data to next request which also puts same data back into temp data.

1
votes

Have you tried <%= Html.HiddenField(...) %>?