Reputation: 3526
I must be misunderstanding something about session. I'm trying to store some information, so let me give the details.
Here's my "container" class that holds a list of business objects. This container is stored in session.
public class MySessionContainer {
private IList<SomeBusinessObjectType> _BusinessObjectList = new List<SomeBusinessObjectType>();
public IList<SomeBusinessObjectType> BusinessObjectList {
get { return _BusinessObjectList; }
set { _BusinessObjectList = value; }
}
}
I have a set of pages that form a wizard/multi-step process, and they all need to access the list of business objects in the container, which is in session.
The first page adds business objects to the list in session, so this sort of code is used to achieve that:
string key = GetKeyForCurrentUser();
MySessionContainer container = (MySessionContainer) Session[key];
SomeBusinessObjectType businessObject = /* Get object from view. */;
container.BusinessObjectList.Add(businessObject);
The generated key is always the same across all pages.
However, when the user gets to the second page, the container is in session as expected but the list of business objects is empty which is not what I expect. If the first page adds a business object, it should be there for the second and subsequent pages... right?
Is there something I am not understanding about session in ASP.net? Why is the container in session but not the list? Is the list not serialized with the container object when ASP.net writes/reads it from session?
Upvotes: 0
Views: 2736
Reputation: 6294
Initalizers can act unexpectedly when serializing an object graph. Try using lazy loaded properties, if you don't want to initialize the collection out of the parent class:
public class MySessionContainer {
private IList<SomeBusinessObjectType> _BusinessObjectList;
public IList<SomeBusinessObjectType> BusinessObjectList {
get { return (_BusinessObjectList ??
(_BusinessObjectList = new List<SomeBusinessObjectType>()) ; }
set { _BusinessObjectList = value; }
}
}
This will allow deserialization to set your list and any getters will never get a null value for your collection.
Also, make sure every object in the graph can be serialized. See here for more information.
This question may also hold some relevance to yours.
Upvotes: 0
Reputation: 866
You need to write it back to the session.
Take a look at the example under Session Variables:
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
Upvotes: 2
Reputation: 995
Session object is not shared across different users so GetKeyForCurrentUser is useless. you can use some simple string for key. objects stored in Session must be serializable thus SomeBusinessObjectType must be serializable too.
Upvotes: 2