Wednesday, April 27, 2011

How to remove ViewState from ASP.NET web page and save in Session using SessionPageStatePersister

By default ViewState is saved inside the web page. In ASP.NET using SessionPageStatePersister ViewState can be saved inside Session instead. This helps in securing the ViewState as well as reducing the size of the web page.

The code to implement the same is overriding the PageStatePersister for the ASP.NET page as displayed below. PageStatePersister provides the base functionality for ASP.NET view state persistence mechanisms.       

protected override PageStatePersister PageStatePersister
{
    get
    {
        return new SessionPageStatePersister(this);
    }
}

The number of ViewState’s that can be saved in Session can be changed by setting historySize as displayed below

<sessionPageState historySize ="20"/>

The difference between web page containing ViewState and when ViewState is inside Session is displayed below. The rows marked in green have ViewState inside Session whereas cells marked in red have ViewState inside web page.

image

No comments:

Post a Comment