Tuesday, September 15, 2009

C#: Efficiently (somewhat) deal with large ViewState

If you are REALLY worried about having the most efficient method of saving ViewState, you should be using the SQLStateServer approach. However if you want a quick hack that will work quite efficiently as long as you do not have hundreds and thousands of active users, you can continue reading this post. Needless to say, I am assuming you have turned EnableViewState to off for whatever controls you could (labels etc), and are concerned about only the ones where you must save the view state.

OK here we go! As we know ASP .Net handles a Cache object (or even Session for that matter) much more efficiently than it does ViewState, just add these two methods in your code behind to save the ViewState to the server cache customized for the user, and restore from it later, in stead of putting it within the page itself.

(Note: You might also consider using a Session object in stead of cache for that matter)

//Just embed these two methods within the codebehind of the page
#region Hack to save and restore ViewState to and from Cache
protected override void SavePageStateToPersistenceMedium(object viewState)
{
// Generate unique key for this viewstate
string stateToSave = "VIEWSTATE#" + Request.UserHostAddress + "#" + DateTime.Now.Ticks.ToString();
// Save viewstate data in cache
Cache.Add(stateToSave, viewState, null, DateTime.Now.AddMinutes(Session.Timeout), TimeSpan.Zero, CacheItemPriority.Default, null);
// Save key in a hidden field
ClientScript.RegisterHiddenField("__VIEWSTATE_KEY", stateToSave);
}

protected override object LoadPageStateFromPersistenceMedium()
{
// Load back viewstate from cache
string savedState = Request.Form["__VIEWSTATE_KEY"];
// Check validity of viewstate key
if (!savedState.StartsWith("VIEWSTATE#"))
throw new Exception("Invalid viewstate key:" + savedState);
object savedCache = Cache[savedState];
// Cleanup the saved cache from server memory
Cache.Remove(savedState);
return savedCache;
}
#endregion

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.