Monday, May 17, 2010

Common Myth Regarding ViewState in ASP.NET

Through this article I want to figure out a very common misconception about viewstate.
Most ASP.NET developers think that the ASP.NET ViewState is responsible for holding the values of controls such as TextBoxes so that they are retained even after postback. But this is not the case.

Let’s take an example to understand above.
Place a web server TextBox control (tbControl) and a web server Label control (lblControl).
Set the “Text” property of label and textbox to “Initial Label Text” and “Initial TextBox Text” respectively and set the “EnableViewState” property of both the controls to false.
Place two button controls and set their text to “Change Label Text” and “Post to Server”. First button changes label’s text by handling button click event and second button only does the postback.

private void btnChangeLabel_Click(object sender, System.EventArgs e)
{
lblControl.Text = "Label's Text Changed";
}

On running this application, you can see the initial texts in the controls as you have set.

Now, change the text in TextBox and set it to “Changed TextBox Text”. Now click the Post to Server button. What happens is that the textbox retain its value, in spite of the ViewState property being set to false.

The reason for this behavior is that ViewState is not responsible for storing the modified values for controls such as TextBoxes, dropdowns, CheckBoxList etc., i.e., those controls which inherit from the IPostBackDataHandler interface. After Page_Init(), there is an event known as LoadViewState, in which the Page class loads values from the hidden __VIEWSTATE from the field for those controls (e.g., Label) whose ViewState is enabled. Then the LoadPostBackData event fires, in which the Page class loads the values of those controls which inherit from the IPostBackDataHandler interface, (e.g., TextBox) from the HTTP POST headers.

Now, on clicking “Change Label Text” button which changes label text programmatically (made by above mentioned event handler), then on clicking “Post to Server”, page reloads and programmatic change was lost i.e. label text changes to initial value – “Initial Label Text”.
This is because the Label control does not inherit from the IPostBackDataHandler interface. So the ViewState is responsible for persist its value across postbacks, and since viewstate has been disabled, the Label loses its value after clicking the “Change Label Text” button.
Now enable the ViewState for the Label control, and you can see the modified value (“Label's Text Changed”) after clicking the same button.

So we conclude that controls which inherit from the IPostBackDataHandler interface will retain their values even if the ViewState has been disabled, as their values are stored in HTTP POST headers.