Home / ASP.NET Wiki / State Management / ViewState

ViewState

 Rate It (10)

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:

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:

<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!

Revision number 12, Friday, July 08, 2011 12:55:44 AM by scngan

Comments

I cannot see half the stuff in the right panel in this page. There seems to be some problem with layout. I am using IE 6.

good to read a refresher notes

nice to learn the basics..

it is not a good practice to use the "ViewState" to store big object that can affect the performance of the web application

Great article for new candidate. i have problem. i don't know how to remove this problem. My Problem is that, i have created a class object in user control and i wanted to keep this object persist till the perticular user access the page, does not matter how many times page post back for that user.but if user goes out from the page object should distroy. for this i have used viewState to keep class object persist on page. i have made my class serializable and keep it in ViewState but the problem is coming and error says like Marked the UserControl class as serializable. Actuly the cause of problem is that in myCreated class has the property to hold the UserControl reference. To avoid this problem i should remove the UserControl property from the class. but i wanted to keep that property in my Created class. Can you tell me how can avoid this problem? Code public partial class UserControl : System.Web.UI.Page { MyCLass myCass; protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack){ myClass = new myClass(this); ViewState["MyClassState"] = myClass; } else { myClass = (MyCLass) ViewState["MyClassState"]; } } } // class code [Serializable] public class MyCLass { public UserControl _uCtrl; public MyCLass(UserControl uCtrl) { _uCtrl = uCtrl; } }

this is Really Great stuff, before this i was stopped at save and load only, here after it was explored more little bit. Thanks and Regards Raja

Related Articles

Asp.Net : __VIEWSTATE Bug !

When you Try this on Asp.net 2.0 WebSite:http://www.YouWebsite/default.aspx?__VIEWSTATE=COUCOU!You will have something like that:Server Error in '/' Application.Runtime ErrorDescription: An application error occurred on the server. The current custom

Developer Guidelines

Things to be taken care by developers while writing code or designing different layers Presentation Layer: Choose your UI elements carefully Optimize Viewstate State management should be effective and optimized well Well Managed Caching Reduce round trips

Access ViewState in Class File

Many times we might need to access Viewstates in classfilewhich is not availablethis is a way to access the Viewstte in Class fileon code Behind%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)