Wednesday, April 22, 2009

How to Store ViewState in Cache Memory

How to Store viewState in Cache Memory.
asp.net provides us pluggable mechanism for storing viewstate to custome store.
this custom can be Session,Cache or FileSystem.we can use any of this to store viewsate.
storing viewstate in Cache memory helps us to reduce pagesize.because on each postback we can reduce bandwidth used to send ViewState data back and forth.
asp.net provide events to plug persistent store for ViewState.

(1)SavePageStateToPersistenceMedium
(2)LoadPageStateFromPersistenceMedium

We can override this for stor viewState data in Cache memory.
To see this In Action Override obove methods in Your code behind.
or Copy Below code.


public partial class EventModel : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
Response.Write("In Is Page Load");
}
protected override void SavePageStateToPersistenceMedium(Object viewState)
{
string ChachedViewStateKey;
ChachedViewStateKey = "__VIEWSTATE_" + Session.SessionID;
Cache.Insert(ChachedViewStateKey, viewState, null, System.DateTime.Now.AddMinutes(Session.Timeout), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
ClientScript.RegisterHiddenField("__VIEWSTATE_Key", ChachedViewStateKey);
}
protected override object LoadPageStateFromPersistenceMedium()
{
string ChachedViewStateKey = Request.Form["__VIEWSTATE_Key"];
if (ChachedViewStateKey == null)
{
return null;
}
else
{
return Cache[ChachedViewStateKey];
}
}
}


we can also save viewstate in file system.

Thanks.