Understanding ASP.NET View State

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 int SomeInteger {
get {
object o = ViewState[“SomeInteger”];
if (o != null) return (int)o;
return 0;
//a default
}
set { ViewState[“SomeInteger”] = value; }
}