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"];
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"];
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.
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.
YourListType ListName = (List<YourListType>)Session["SessionName"];
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
Source: Stackoverflow.com