Thursday 24 November 2011

Save ViewState at server side to reduce Page Size

Some time we have lots of heavy controls (like GridView,DataGrid) which emits lots of ViewState information on the page. This results to increase in Page size and apparently it would reduce the page performance.
So to reduce the page size ViewState can be stored on Server side which would reduce the page size.
We need to override SavePageStateToPersistenceMedium method to save the ViewState at server side and LoadPageStateFromPersistenceMedium method to retrieve the ViewState.

Note: These two methods needs to be overridden in code behind file of ASP.Net page.

Sample Code snippet.

protected override void SavePageStateToPersistenceMedium(object state)
{
try
{
string VSKey = "VIEWSTATE_" + base.Session.SessionID + "_" +
Request.RawUrl + "_" + DateTime.Now.Ticks.ToString();
Cache.Add(VSKey, state, null, DateTime.Now.AddMinutes(Session.Timeout),
Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
ClientScript.RegisterHiddenField("__VIEWSTATE_KEY", VSKey);
}
catch
{
base.SavePageStateToPersistenceMedium(state);
}
}

protected override object LoadPageStateFromPersistenceMedium()
{
string VSKey = Request.Form["__VIEWSTATE_KEY"];
return Cache[VSKey];
}

No comments:

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...