1

I learned that Sessions are no longer the recommended way to preserve data in ASP MVC and rather we should move to ViewData (from controller to View) and TempData ( for one postback only). The only reason why we shouldn't use Session is to maintain the Testability (MVC supports TDD, thus HTTPContext.Session wouldn't resolve while running TestMethods).

But the purpose solved widely by Sessions are still not solved by ViewData or TempData. Session saves the context for throughout the user Session.

I am still not able to collect the correct recommendations and Alternatives for Sessions in MVC. Might be I am mistaken in understanding the correct picture. I would appreciate any links to the discussions or any suggestions from you guys.

This will help me to decide, using Session for the purpose it has been used with WebForms or we should go for rearchitecting the current application so that we can go with Session only where mandatory.

Thanks Sumeet

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Sumeet
  • 905
  • 1
  • 14
  • 32
  • 1
    If you used sessions *correctly* (i.e. for storing per-session information related to the *session user* with a session-wide scope, and not data related to the functionality of the application) in ASP.NET Web Forms, you should do it the same way in ASP.NET MVC. But the odds are you were using sessions in ASP.NET Web Forms as a general storage for whatever, for which ASP.NET MVC has other mechanisms (as you write). – bzlm Feb 22 '12 at 08:16

1 Answers1

3

Session is still widely in use in MVC.

In order to make your code more testable, you can provide an abstraction (e.g. Interface) to Session, and then inject it into your controller - you can then provide mocked or stubbed 'sessions' to your controller.

But I would stick to using ViewModel or ViewData to communicate to your views - i.e. view shouldn't be accessing Session directly.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 1
    +1 I was about to write much the same. I still make use of session in ASP.NET MVC apps. e.g. just the other day I needed to persist a user's filter settings for various sections of an MVC app (in this case selected values in dropdown lists) so that the filter would be the same when they returned to that section of the app. Using session provided the easiest way of doing this. – Tom Chantler Feb 22 '12 at 08:09
  • 1
    @Dommer Nothing wrong with sessions as long as performance isn't an issue. I do completely agree with nonnbs point though about working through an abstraction though. I tend to stay away from ViewBag/ViewData though: http://completedevelopment.blogspot.com/2011/12/stop-using-viewbag-in-most-places.html – Adam Tuliper Feb 22 '12 at 14:56
  • Yes I have never used ViewBag/ViewData for the same reasons as you. I hadn't seen your blog before, looks like we could rant/agree/etc over a lot of the same stuff... ;-) – Tom Chantler Feb 22 '12 at 15:20