Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

ViewState

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
28 Feb 2014CPOL5 min read 37.5K   12   3
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:

HTML
<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
<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:

VB
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
C#
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:

HTML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

755 members

Comments and Discussions

 
QuestionMost annoying thing of viewstate. Pin
A Chatterjee28-May-14 7:04
professionalA Chatterjee28-May-14 7:04 
QuestionI would not store the viewstate in a session variable Pin
Kees van Spelde1-Mar-14 8:01
professionalKees van Spelde1-Mar-14 8:01 
AnswerRe: I would not store the viewstate in a session variable Pin
HaBiX3-Mar-14 11:38
HaBiX3-Mar-14 11:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.