简体   繁体   中英

Adding Item to Generic List in Session

I have a session helper so that my session vars are strongly typed:

public sealed class SessionHelper
{
    private static HttpSessionState Session
    {
        get
        {
            return HttpContext.Current.Session;
        }
    }

    public static List<TestObject> Tests
    {
        get
        {
            List<TestObject> objects = new List<TestObject>();
            if (Session["Tests"] != null)
            {
                objects = (List<TestObject>)Session["Tests"];
            }

            return objects;
        }

        set
        {
            Session["Tests"] = value;
        }
    }
}

Now I am trying to add an item to the TestObjects List so I thought I could just do:

SessionHelper.Tests.Add(new TestObject("Test name", 1));

But when I step through the code and look at the SessionHelper.Tests after the above line is run, the list count remains at 0.

If I do:

List<TestObject> tests = SessionHelper.Tests;
tests.Add(new TestObject(testName, version));
SessionHelper.Tests = tests;

Then it works properly.

Why can't I add the test object directly to the SessionHelper ?

Session["Tests"] is null when you start. Therefore SessionHelper.Tests returns a new, empty list; however, this new list is not in the session object yet. Therefore SessionHelper.Tests will return a new, empty list every time. Store the new list in the session object after creating it.

public static List<TestObject> Tests
{
    get
    {
        List<TestObject> objects = (List<TestObject>)Session["Tests"];
        if (objects == null)
        {
            objects = new List<TestObject>();
            Session["Tests"] = objects; // Store the new list in the session object!
        }
        return objects;
    }

    set // Do you still need this setter?
    {
        Session["Tests"] = value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM