Make sure you really want those objects to go into the session, though, because they will remain there as the user navigates around your site. If you only want those objects to be available for one page load, you may want to take another approach.
The solution I've come up with is to reserve one slot in the session for a System.Collections.Hashtable that gets cleared every time you load a new page. I put page-specific objects in there, while I put things like user information / preferences directly in the session.
Below, I've put an example class that does this. Has anyone else come up with a different solution for doing something similar?
- using System;
-
using System.Collections;
-
using System.Web;
-
-
public class PageManager
-
{
-
const string CONTEXT = "context";
-
-
public object GetFromContext(Page page, string key)
-
{
-
return ((Hashtable)page.Session[CONTEXT])[key];
-
}
-
-
public void PutIntoContext(Page page, string key, object value)
-
{
-
((Hashtable)page.Session[CONTEXT])[key] = value;
-
}
-
-
public object GetFromSession(Page page, string key)
-
{
-
return page.Session[key];
-
}
-
-
public void PutIntoSession(Page page, string key, object value)
-
{
-
page.Session[key] = value;
-
}
-
-
//this should get called on every page load
-
public void ClearContext(Page page)
-
{
-
page.Session[CONTEXT] = new Hashtable();
-
}
-
}