How to use <T> Session List in asp.net to store a value

i made one property as follows:

public static List<Message> _SessionStore; public static List<Message> SessionStore { get { if(HttpContext.Current.Session["MyData"]==null) { _SessionStore = new List<Message>(); } return _SessionStore; } set { HttpContext.Current.Session["MyData"] = _SessionStore; } } 

I want to add the value SessionStore.Add() and get SessionStore.Where() but I got an error while doing this add and receive

I did SessionStore.Add first (comment); somewhere i got this error

  List<Message> msglist = HttpContext.Current.Session["MyData"] as List<Message>; if(msglist.Count>0) 

I can not access msglist

can someone fix my property so that I can use this List from any page to add and receive values

+4
source share
3 answers

It seems you forgot to put the SessionStore in an ASP.NET session, for example:

 if(HttpContext.Current.Session["MyData"]==null) { _SessionStore = new List<Message>(); // the following line is missing HttpContext.Current.Session["MyData"] = _SessionStore; } 

BTW: I think the _SessionStore field _SessionStore not required. That should be enough:

 public static List<Message> SessionStore { get { if(HttpContext.Current.Session["MyData"]==null) { HttpContext.Current.Session["MyData"] = new List<Message>(); } return HttpContext.Current.Session["MyData"] as List<Message>; } } 

And then, when you want to use the message list, you should access it through the SessionStore property, and not through HttpContext.Current.Session :

 List<Message> msglist = NameOfYourClass.SessionStore; if(msglist.Count>0) 
+2
source

You did not save the session

 get { if(HttpContext.Current.Session["MyData"]==null) { HttpContext.Current.Session["MyData"] = new List<Message>(); } List<Message> list = HttpContext.Current.Session["MyData"] as List<Message>; return list; } 
0
source

Using your code

  public static List<Message> _SessionStore; public static List<Message> SessionStore { get { if(HttpContext.Current.Session["MyData"]==null) { _SessionStore = new List<Message>(); } return _SessionStore; } set { HttpContext.Current.Session["MyData"] = value; _SessionStore = value; } } 

This will save the value that you set for SessionStore in the private version, and the session

0
source

Source: https://habr.com/ru/post/1444786/


All Articles