Dec
13
2005
Page-level caching, or passing data between different ascx:s
Posted by admin under
ASP.NET articles
Since building up a webpage from many different ascx-files is a very good idea instead of building the pages totally in the aspx-file you soon come up with the need of communication between the different ascx-pages. In other words, you need the exact same data strucure used in one ascx file in another.
In my early days of ASP.NET I (in my aspx-file) instantiated a class called CurrentState which I then passed on to each ascx file loaded with LoadControl.
However there is a much smoother way, and it works like a cache valid for the current request.
Lets look at some code, I still use a CurrentState class but never instatiates it and pass it along, instead the class only contains static methods, like:
public static ObjClasses.MessageList Messages
{
get
{
ObjClasses.MessageList oList =
System.Web.HttpContext.Current.Items["Meddelanden"] as ObjClasses.MeddelandeClassList;
if ( oList == null )
{
oList = new ObjClasses.MessageList(); oList.Open("", "datum", "desc"
System.Web.HttpContext.Current.Items["Meddelanden"] = oList ;
)
return oList;
}
}
My ascx-files, when they need the list of messages, they just call
oDataGrid.DataSource = ObjClasses.CurrentState.Messages
And the database query (hidden inside the oList.Open call) will only be made once for each page, regardless of how many ascx-files calling this function.
The secret is using the System.Web.HttpContext.Current.Items collection which simply is a cache (can store any type of object) and it will be erased upon next page request.
First we check to see if there is a collection in this cache:
ObjClasses.MessageList oList = System.Web.HttpContext.Current.Items["Meddelanden"] as ObjClasses.MeddelandeClassList;
If not we creates the collection and stores the collection in the page level cache: ... ... System.Web.HttpContext.Current.Items["Meddelanden"] = oList;
And next time (when another ascx-file called from the same aspx-file requests the same list) it will be available and no database query will be made.
Of course you could do it the other way as well, now we only makes sure data is read once from the database per request, but we could of course have a set{} part of the query and and have ascx-files make information available for other ascx-files.