By default, ASP.NET web forms maintain the state of their server controls across HTTP requests. This control-level caching is called ViewState and is done automatically for you so that control values persist between postbacks. This state is actually stored on the page as a base-64 encoded string value in a hidden input control called _VIEWSTATE which will look something like this:
Effect on performance
Of course when anything is made this simple, there has to be a penalty and it’s no different here. Maintaining view state for every single server control (controls with the
runat="server" attribute) has a considerable cost in terms of how much data is posted back to the server each time. Using Firebug to measure the size of a page containing a few simple server controls, it detected over 1,000 bytes were sent in the server request. This doesn’t sound much but if your page contains a complex server control such as a grid with lots of rows and columns, the amount of data being posted back each time will escalate rapidly.
Fortunately view state can be disabled at the following granular levels to reduce the amount of unnecessary data being submitted per request:
To disable view state at site-level, modify the pages element in the web.config. You can then enable view state on individual controls which require it.
<pages enableViewState="false" />
To disable view state for a specific page, set the EnableViewState attribute in the page directive.
<%@ Page EnableViewState="false" %>
And to disable view state for a particular control, set its EnableViewState attribute.
<asp:TextBox runat="server" EnableViewState="false" />
Of course the final word in minimising data transfer and maximising performance is not to rely so much on ASP.NET server controls. They are convenient but inefficient.
Page ViewState property
View state is not restricted to just controls. Because
System.Web.UI.Page derives from
System.Web.UI.Control, it also has the
ViewState property which means you can implement variables and properties in your page’s code-behind file which persist between postbacks. The ViewState property simply maintains a set of key/value pairs which can be accessed on the server.
Here is a typical page property implemented in the code-behind file, using ViewState to persist its value across separate requests. Because ViewState stores value objects as a reference to a
System.Object, you will need to cast/convert the value in your property getter:
This can be enormously useful for situations where you need to support logic for a UI element which goes beyond the basic features provided by the control itself (e.g. persisting user-selected items in a list between refreshes).
Sharing data between server and client
Web form markup:
<asp:HiddenField ID="hiddenField" runat="server" />
var someData = $("#hiddenField").value;