ALAN
ALAN

Reputation: 495

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

i made one property like this :

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 value SessionStore.Add() and get SessionStore.Where() but i got error while doing this Add And Get

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

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

i am not able access msglist

can anybody fix my property in way that i can use this List from anypage to add and get values

Upvotes: 4

Views: 6267

Answers (3)

M4N
M4N

Reputation: 96571

Seems you forgot to put the SessionStore into the ASP.NET session, e.g:

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 is not required. This 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, where you want to use the list of messages, you should access it via the SessionStore property, instead of via HttpContext.Current.Session:

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

Upvotes: 2

Riaan Walters
Riaan Walters

Reputation: 2676

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 store the value you set to SessionStore in the private version and the session

Upvotes: 0

codingbiz
codingbiz

Reputation: 26386

You did not store into 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;
}

Upvotes: 0

Related Questions