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];
}

2 Comments

  • If i use this code, In submitting record i am getting the following error:

    "The state information is invalid for this page and might be corrupted."

    I have just copied and pasted the above code in my code behind page. Is that any changes i have to make. I am using ASP.NET 2.0.

  • I had the same issue. The resolution I found and is working for me is...comment the second line of code ie.,
    "// Keep the viewstate hidden variable but with no data to avoid error
    RegisterHiddenField("__VIEWSTATE", "");".

    That is reinserting multiple tags of __VIEWSTATE instead of actually replacing/working with one tag.




Comments have been disabled for this content.