ViewStateMode in ASP.Net 4.0

Posted by sreejukg on ASP.net Weblogs See other posts from ASP.net Weblogs or by sreejukg
Published on Tue, 06 Apr 2010 04:59:00 GMT Indexed on 2010/04/06 5:23 UTC
Read the original article Hit count: 672

Filed under:
|

When asp.net introduced the concept of viewstate, it changed the way how developers maintain the state for the controls in a web page. Until then to keep the track of the control(in classic asp), it was the developer responsibility to manually assign the posted content before rendering the control again. Viewstate made allowed the developer to do it with ease. The developers are not bothered about how controls keep there state on post back.

Viewstate is rendered to the browser as a hidden variable __viewstate. Since viewstate stores the values of all controls, as the number of controls in the page increases, the content of viewstate grows large. It causes some websites to load slowly.

As developers we need viewstate, but actually we do not want this for all the controls in the page. Till asp.net 3.5, if viewstate is disabled from web.config (using <pages viewstate=”false”/> ..</pages>), then you can not enable it from the control level/page level. Both <%@ Page EnableViewState=”true”…. and <asp:textbox EnableViewState=”true” will not work in this case.

Lot of developers demands for more control over viewstate. It will be useful if the developers are able to disable it for the entire page and enable it for only those controls that needed viewstate. With ASP.NET 4.0, this is possible, a happy news for the developers. This is achieved by introducing a new property called ViewStateMode.

Let us see, What is ViewStateMode – Is a new property in asp.net 4.0, that allows developers to enable viewstate for individual control even if the parent has disabled it. This ViewStateMode property can contain either of three values

  1. Enabled- Enable view state for the control even if the parent control has view state disabled.
  2. Disabled - Disable view state for this control even if the parent control has view state enabled
  3. Inherit - Inherit the value of ViewStateMode from the parent, this is the default value.

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

Find the example below.

Page directive - <%@ Page Language="C#"  EnableViewState="True" ViewStateMode="Disabled" .......... %>

Code for the control  - <asp:TextBox runat="server" ViewStateMode="Enabled" ............../>

Now the viewstate will be disabled for the whole page, but enabled for the TextBox.

ViewStateMode gives developers more control over the viewstate.

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about Web Development