November 03, 2008

What is there in _VIEWSTATE field?


First of all _VIEWSTATE is a field(HTML Element) and its different from what we think about a ViewState.

Now, Will you have a value stored in the _VIEWSTATE field if it is a blank ASP.NET Page or ViewState completely diabled. The answer is yes. If we see the viewsource of this blank page we can find a small serialized value. The reason is the page itself saves approximately 20 bytes of information into the _VIEWSTATE field, which it uses to distribute postback data and viewstate values to the correct controls upon postback.


    The data stored in the _VIEWSTATE field consists of the following
  • Data stored by developers using the Viewstate[""] indexer.
  • Programmatic changes to the control state.

OK, so let us assume that we have a web page with only a Label control on it. Now, let us say that at design time, if we set the “Text” property of the Label to “statictext”. Now, load the page and open the View Source page. We can see the __VIEWSTATE field. Do you think “statictext” is saved there? The answer is, for sure, not. Recall that static properties of controls are assigned at the generated class. So, when the page is requested, the values stored in the generated class are displayed. As such, static properties that are set at design time are never stored in the __VIEWSTATE field. However, they are stored in the generated compiled class, and thus they show up when rendering the page.

Now if we change the label "Text" property to "dynamicText" in the page load then this "dynamicText" is saved in the _VIEWSTATE field. The reason is we have changed the label's "Text" property at run-time and this is done at the page load time during which the tracking of viewstate is enabled(TrackViewState() is enabled in the InitComplete event), the "Text" property is marked as "Dirty" and thus the "SaveViewState" will save the controls new value in the _VIEWSTATE field!

Keep Smiling and Programming!!

0 comments: