ViewStateMode and EnableViewState

By Peter Bromberg

Often developers can get confused about the various settings for ViewState on pages and individual controls. This is because the settings themselves are confusing!

ViewStateMode
You can use the ViewStateMode property to enable view state for an individual control even if view state is disabled for the page.

Control.EnableViewState gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client

To disable view state for a page but enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.

The default value of the ViewStateMode property for a page is Enabled. The default value of the ViewStateMode property for a control in a page is Inherit. As a result, if you do not set this property at either the page or the control level, the value of the EnableViewState property determines view-state behavior.

The ViewStateMode property of a page or a control has an effect only if the EnableViewState property is set to true. If the EnableViewState property is set to false, view state will be turned off even if the ViewStateMode property is set to Enabled.

So the correct way to handle enabling ViewState only on a checkbox would be:

1. Leave EnableViewState="true" (the default) everywhere.
2. Set ViewStateMode="false" on master page. This way each derived page and control inherit ViewStateMode and do not output viewstate.
3. Enable viewstate only on the checkbox by setting ViewStateMode="true".

ViewStateMode and EnableViewState  (1999 Views)