Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a generic list from session?

I have a list that I put in session:

Session.Add("SessionList", mylist);

How to retrieve it back from the session?

like image 382
Ali Hasan Avatar asked Nov 19 '11 13:11

Ali Hasan


People also ask

Can we store list in session?

Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state): Session["test"] = myList; You should cast it back to the original type for use: var list = (List<int>)Session["test"]; // list.

How can I see all session variables in asp net?

In this post I am going to discuss about how you can get list of all active Session Variables in ASP.NET Application. The easiest way to get the details of session variable is using “Tracing” . If you enable the “ Tracing ” for your application, you can get list of all Active Session variables .


1 Answers

var list = Session["SessionList"] as List<whatevertypeYouUsed>;

if (list != null){
   // blah...
}

I prefer to use the as keyword since there is no 100% guarantee that the Session will contain the list (due to application pool refresh, website being restarted, etc). Gives you that extra bit of defence to avoid a NullReferenceException.

like image 151
Jason Evans Avatar answered Oct 08 '22 14:10

Jason Evans