Tuesday, January 5, 2010

Viewstate management in ASP.Net 4.0

In ASP.NET 4.0 we have some very interesting new enhancements and new features.

I will try to talk about all of them in separate posts.

In this post I will talk about Viewstate management in ASP.NET 4.0. 

Let’s have a look first what really Viewstate is and what it really does.Unless you move to a new paradigm for building web applications like ASP.NET MVC you must have a good knowledge of Viewstate.
Viewstate represents the state of the page when it was last processed on the server. We use it to retain values across two successive requests for the same page. It is a hidden field added to the page and is restored on the server before the page request is processed. The Viewstate information travels back and forth with the page itself, but contains no visual elements that need to be rendered. So you must be thinking that this is fantastic news for the web developer. But (there is always a but), the extra information in the Viewstate adds to the size of the page and the information that travels down the wire. I have seen web pages that have an additional 20Kbytes of Viewstate information.

Every .aspx page derives from the Page class or Page control and extends it. The default value for the EnableViewState property for the page is True. Through that property we can get or set(enable-disable)  the view state of the control. However, EnableViewState property is ignored for child controls. So if we have EnableViewState=True for the page, which is True by default, all the child elements on that page will have EnableViewState=True for their viewstate property. So if we type this  txtname.EnableViewState = false , this will have no effect, since the textbox is the child of the .aspx page we are designing.
There is a mistake here. The opposite is actually true.If we disable ViewState on page level, you cannot enable it on child controls. if you go to the web.config and type

then if you try to enable it on child controls is impossible.

So to be absolutely clear, in asp.net 1.1,2.0.3.5 if you have ViewState enabled on page level , you can have it disabled for some controls you choose.

But if you disable it on page level(or application level) you cannot enable it for individual controls.

In ASP.NET 4.0 we have the ViewState property. There are 3 values for this property:enabled, disabled, inherit .

We can use this property to enable Viewstate for an individual control even if Viewstate is disabled for the page. We can disable the Viewstate for a control even if it is enabled on a page level.

0 Please Share a Your Opinion.: