user1197114
user1197114

Reputation: 63

Storing and Accessing Dictionary values in session

I have a dictionary like below

Dictionary<Tuple<int, int>, bool> sampleDict= new Dictionary<Tuple<int, int>, bool>();

which I added in Session

if (!IsPostBack)
{
   HttpContext.Current.Session.Add("SessionsampleDict", sampleDict);
}

NOw I need to add values into Dictionary, so my code goes like.

sampleDict.Add(DictKey, true);

NOw issue is when I am coming back to my page using postback, I am loosing all my data in sampleDict.

What I am doing wrong here ? How to add values of dictionary on session ?

Upvotes: 1

Views: 3249

Answers (4)

sujith karivelil
sujith karivelil

Reputation: 29036

sampleDict will not be in session, only its values are copied to session. You need to reassign the value to session variable after modifying them. or else you can try like this:

((Dictionary<Tuple<int, int>, bool>)HttpContext.Current.Session["SessionsampleDict"]).Add(DictKey, true);

Upvotes: 3

Tomas Chabada
Tomas Chabada

Reputation: 3019

When you save dictionary in session and then you modify dictionary, session object will not be updated, since it is no more the same object. Session can be stored in database, redis or in another storage, so it is only clone to original object.

Upvotes: 0

user1429080
user1429080

Reputation: 9166

Try this:

Dictionary<Tuple<int, int>, bool> _sessionDict;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack || !(Session["SessionsampleDict"] is Dictionary<Tuple<int, int>, bool>))
    {
        Dictionary<Tuple<int, int>, bool> localDict = new Dictionary<Tuple<int, int>, bool>();
        Session["SessionsampleDict"] = localDict;
    }
    _sessionDict = (Dictionary<Tuple<int, int>, bool>)Session["SessionsampleDict"];
}

Now you can access the Dictionary using the local ref _sessionDict elsewhere in your page.

Upvotes: 3

Michael Curry
Michael Curry

Reputation: 989

I'm guessing that when you add the sampleDict to your session you are making a copy of it and storing it, so when you call

sampleDict.Add(...)

It is not updating the one in your session.

You may have to either update the one in your session every time you update the other one, or find a way to manipulate only the one in your session.

sampleDict.Add(...);
HttpContext.Current.Session["SessionsampleDict"] = sampleDict;

Something like that?

Not too familiar with the Session class but I've made a rough guess. Let me know how it goes :)

Upvotes: 0

Related Questions