ViewState ASP.NET State Management

Enable View State?

You may do so on the machine, application, page and control level. First, you must have a server side form (<form runat="server">). By default view state is enabled. A quick peek into machine.config :

<pages enableViewState="true" enableViewStateMac="true" ... />

The nature of machine.config prescribes general settings for all applications. In other words since view state is enabled on the machine level it is enabled on the application, page and control level. Thus each server control has view state enabled by default.

Disable View State?

Again, you may do so on the machine, application, page and control level. To disable view state of an individual control set its EnableViewState to false:

<asp:Label id=Label1 runat="server" EnableViewState="false" />

Page Lifecycle Is It Safe To Use View State?

In the page lifetime cycle view state is available between the Init and PreRender events. If you need to dig deeper into the class behind the view state check out StateBag and StateItem.

Protecting View State:
  • Set enableViewState="true"
  • Set machineKey validation type to 3DES. This causes ASP.NET to encrypt the view state.
web.config should have these two entries:

<pages enableViewState="true" enableViewStateMac="true" />
<machineKey ... validation="3DES" />

"View State Is Invalid" Error Message When You Use Server.Transfer

Suppose you have a web page. The first page has a MAC appended to its view state . Now, what if you need to call Server.Transfer and you want to preserve its QueryString and the Form collection? You may do so by calling an overloaded Server.Transfer and passing true as its second parameter.

Next, when this second page is invoked it receives the view state of the calling web form in its __VIEWSTATE hidden field. The view state authentication check will fail since the newly arrived view state is invalid on the second page.
Tags: , ,
Hot on Web:


About author