Store List to session

C#asp.netListSession

C# Problem Overview


is it possible to store list to session variable in Asp.net C# ?

C# Solutions


Solution 1 - C#

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.Add(something);

As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.

Solution 2 - C#

Yes. Which platform are you writing for? ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

myList = (List<string>)Session["var"];

Solution 3 - C#

I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:

HttpContext.Current.Session.Add("currentUser", appUser);

and

(AppUser) HttpContext.Current.Session["currentUser"]

Otherwise the compiler was expecting a string when I pointed the object at the session object.

Solution 4 - C#

Try this..

    List<Cat> cats = new List<Cat>
    {
        new Cat(){ Name = "Sylvester", Age=8 },
        new Cat(){ Name = "Whiskers", Age=2 },
        new Cat(){ Name = "Sasha", Age=14 }
    };
    Session["data"] = cats;
    foreach (Cat c in cats)
        System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name);     //DEBUGGG

Solution 5 - C#

YourListType ListName = (List<YourListType>)Session["SessionName"];

Solution 6 - C#

public class ProductList
{
   public string product{get;set;}
   public List<ProductList> objList{get;set;}
}
   
ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});

now assign obj to session

Session["Product"]=obj;

for retrieval of session.

ProductList objLst = (ProductList)Session["Product"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAvinashView Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#Paul McLeanView Answer on Stackoverflow
Solution 3 - C#Don-e MersonView Answer on Stackoverflow
Solution 4 - C#Alejandro GarciaView Answer on Stackoverflow
Solution 5 - C#Marwah AbdelaalView Answer on Stackoverflow
Solution 6 - C#Ubaid Ur RehmanView Answer on Stackoverflow