0

I've been working with MVC 3 for a little while at work and have been reviewing my code quite a bit. I'm using the session to store data I need across all actions/views.

I feel this is a bad idea, though I'm not entirely understanding of why. So I started reading around and found this post: Session variables in ASP.NET MVC

I'm currently accessing the session in my controller in this manner,

private SelectedReport Report
{
   get
   {
        return Session["Report"] as SelectedReport;
   }
   set
   {
        Session["Report"] = value;
   }
}

then Accessing it with this.Report

I've read that the way above is not optimal/good but I'm not certain why.

Why is my way not good/optimal? Why is the way in the link provided better?

(This might be better posed as a conceptual question but i'm not sure how to ask it that way, there are a few web/mvc concepts I think I'm missing. I was kind of just thrown into MVC/Web with no prior knowledge and was never sure where to start).

Community
  • 1
  • 1
Shelby115
  • 2,816
  • 3
  • 36
  • 52

1 Answers1

1

For error handling there are several libraries that can simplify things for you. But beyond that, storing things on the session should only be done where you need the object In several places

Ideally if you need to expose one object from one view to the other, you could use a common base model that includes what the views need, or add stuff to the ViewData object instead of the session object.

And for error handling, fatal errors should be trapped in global.asax, and for warnings, I in particular use a base model class for all views that includes a warnings collection that is shown via master page.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Carlos Grappa
  • 2,351
  • 15
  • 18
  • I clarified my post a bit, I wasn't really asking about how to do error handling I was asking why it is bad to use the session variable the way I am. Sorry for the confusion. – Shelby115 Jun 13 '13 at 16:09
  • It doesn't really matter how you use it, in the end its the same. Is your way optimal? No, but storing objects in session (specially objects that tend to change) never is. Is it good? yes, it its, you're encapsulating the session acces behind a property, you could use another class and have a singleton an all that, but in the end its just the same thing you did here. – Carlos Grappa Jun 13 '13 at 16:33