Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ViewState

0.00/5 (No votes)
28 Feb 2014 1  
ViewState is the mechanism that allows state values to be preserved across page postbacks.Because of the stateless nature of web pages, regular

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

ViewState

ViewState is the mechanism that allows state values to be preserved across page postbacks.

Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks.  When we need a page variable to maintain its value across page post backs, we can use ViewState to store that value.  Values stored in ViewState will be serialized and sent to the client browser as the value of a hidden form input.  When you view the page source (in your browser) of a page the uses ViewState, you may see this hidden viewstate input which will look something like this:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTM1ODM3Nj......." />

This single hidden field contains all the viewstate values for all the page controls. This is an important aspect of viewstate that you need to consider. 

Because viewstate is (by default) sent to the client browser and then returned to the server in the form of a hidden input control on your page, storing a significant amount of data in viewstate can increase your page size and can affect your page performance.

To disable ViewState for a control, you can set the EnableViewState property to false (In asp.net 2.0, ViewState is enabled by default).  When ViewState is disabled for any control, it will also automatically be disabled for all child controls of that control. 

Example:

<asp:Label ID="lblRequestCount" runat="server" EnableViewState="false"></asp:Label>

This does not mean that you should avoid viewstate. You should however, always be aware of what you are storing there and how it affects your overall page size.

Some people hate ViewState, others love it. Either way, you have control over your ViewState, so take control!

Example 

One simple way to store small values in viewstate is to use a property instead of a member variable.  This property can use viewstate to store its value rather than a member variable that would lose the value over a postback. For example, storing an Integer in viewstate can be accomplished like this:

Public Property SomeInteger() As Integer

    Get

        Dim o As Object = ViewState("SomeInteger")

        If Not o Is Nothing Then Return DirectCast(o, Integer)           

        Return 0 'a default

    End Get

    Set(ByVal value As Integer)

        ViewState("SomeInteger") = value

    End Set

End Property
public int SomeInteger {

    get {

        object o = ViewState["SomeInteger"];

        if (o != null) return (int)o;

        return 0;

        //a default

    }

    set { ViewState["SomeInteger"] = value; }

}

 

Articles

Links

Tools

 

Persisting View State Outside the Page

In certain cases, typically when you have large number of server controls in a page or store large amount of custom data in view state, the size of the page view state data could grow high. As you know, a page's view state data is encoded and stored in a HTML hidden element and sent as part of the the page to the client. Having a large view state could impact the performance of the web application because it increases the total page size (which includes the encoded view state) to be downloaded by the client. One way to improve the page size is obviously to control what goes inside the view state. But, in certain scenarios you wont have much options but to live with the way it is. In such cases, you can compress the view state data or store the view state elsewhere outside the page, like session state. Yes, ASP.NET does provide ways to customize where the view state is stored.

In order to customize the persistence part of the page view state, you need to override the SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium methods of the Page class. SavePageStateToPersistenceMedium is called when the view state is ready to be persisted in the page life cycle; ASP.NET calls this method passing the view state object and it is up to us what we want to do with this object as long as we are able to give it back to ASP.NET when it asks for it via the latter method, LoadPageStateFromPersistenceMedium. As the name implies, this method does the reverse of the former in terms of state persistence customization The following code sample shows how you can store the view state in a session state variable, keyed by the session ID:

protected override object LoadPageStateFromPersistenceMedium ()

{
    return (new LosFormatter().Deserialize ((string)Session[Session.SessionID]));
}

protected override void SavePageStateToPersistenceMedium (object state)
{
    LosFormatter los = new LosFormatter();
    StringWriter sw = new StringWriter();
    los.Serialize (sw, state);
    string vs = sw.ToString ();
    Session[Session.SessionID] = vs;
}

Once the above code is in place, the HTML hidden element meant for view state data in the page should be empty:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />

Other option to explore is to compress the view state size and send it as part of the page in the form of a HTML hidden element, the default way.

Another major improvement is to store the ViewState into a persistent medium instead of just use the Session variable to hold the ViewState. This technique was explored in Scott Mitchell's article, UnderStanding ASP.NET ViewState, on MSDN where he explains in details everything about ASP.NET ViewState and the algorithm to store the ViewState in a persistent medium. This algorithm was implemented by Bilal Haidar at http://www.aspalliance.com/ and the details of this technique can be viewed by following the following link: Store View State in a Persistent Medium, the Proper Way.

Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here