Tuesday, 15 May 2007

Storing ViewState into Session

HTTP requests and responses are inherently stateless. To maintain state between HTTP requests, ASP.NET server pages can store Page state. This state, called ViewState, consists of page and control settings and data that make the page and controls appear as if they are the same ones that the user saw and interacted with on their last round trip to the page. Why would you want to store ViewState into session? 1)You have a page using lots of panels/controls resulting in a large viewstate, which is affecting perforrmace during postbacks. 2)You are serving pages to small devices that have limited client-side resources or use a markup language that does not support a hidden field element. Several mechanisms exist to store ViewState between successive requests to the same page, the abstract PageStatePersister class represents the base class for these state storage mechanisms in .Net 2. By default HiddenFieldPageStatePersister is used to keep ViewState in a hidden input element, __VIEWSTATE, which is way .Net 1/1.1 worked. To use a different mechanism, such as the bundled SessionPageStatePersister (which stores page state into session), just override the System.Web.UI.Page PageStatePersister property:
protected override PageStatePersister PageStatePersister
{
   get
   {
      return new SessionPageStatePersister(this);
   }
}
More on ViewState It is worth mentioning that you may want to look into using PageAdapters instead of overriding the System.Web.UI.Page PageStatePersister property, the MSDN PageAdapter page will get you started :) A good ViewState page that explains everything clearly is on Dave Reed's blog site. A handy ViewState decoder tool by Vasudevan Deepak Kumar. Technorati Profile

No comments: