Tip on Saving ViewState on Server
Here's a tip relating to saving viewstate on the server I received from Johan Åhlén:
Thank you for a good article on how the viewstate works!
I have also been experimenting with how to save the viewstate to the server. Just having a session variable holding the viewstate results in the problem that the viewstate gets out of synchronisation with the page if users click back, etc. What has worked best for me so far is storing multiple viewstates in the cache, and having a hidden field on the page telling which viewstate to use. A possible improvement is to reduce memory usage by reducing the number of simultaneous viewstates that each user can have.
protected override void SavePageStateToPersistenceMedium(object viewState)
{
// Generate unique key for this viewstate
string str = "VIEWSTATE#" + Request.UserHostAddress
+ "#" + DateTime.Now.Ticks.ToString();
// Save viewstate data in cache
Cache.Add(str, viewState, null, DateTime.Now.AddMinutes(Session.Timeout),
TimeSpan.Zero, CacheItemPriority.Default, null);
RegisterHiddenField("__VIEWSTATE_KEY", str);
// Keep the viewstate hidden variable but with no data to avoid error
RegisterHiddenField("__VIEWSTATE", "");
}protected override object LoadPageStateFromPersistenceMedium()
{
// Load back viewstate from cache
string str = Request.Form["__VIEWSTATE_KEY"];
// Check validity of viewstate key
if (!str.StartsWith("VIEWSTATE#")) {
throw new Exception("Invalid viewstate key:" + str);
}
return Cache[str];
}