Tuesday, August 17, 2010

View State for TextBoxes, CheckBoxes, DropDownLists

There is a common misunderstanding among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. I was one of them.

This is not the case, because the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.

In the page lifecycle, LoadPostBackData happens after LoadViewState stage. They are independent. The value of a textbox is restored in LoadPostBackData stage. If the view state for this textbox is enabled, then what happens in LoadViewState? Yes, the textbox could got a value, but that could be the wrong one, because the information in the view state represents the state before submission. For example, if the textbox’s value is “Hello my world” before you take any action to the page; at this moment, in the viewstate, it is “Hello my world”. Then from the browser, you change it to “Hello your world”, and submit the page. A new trip of the page life cycle happens. As we have known now, LoadViewState happens before LoadPostBackData. Guess what is the textbox’s value in the LoadViewState stage gotten from view state? It is “Hello my world” rather than “Hello your world”. Fortunately, LoadViewState follows, so that you can get the correct “Hello your world”. Untill the moment before the control is rendered, the viewstate is updated to “Hello your world”. Have you seen enabling the ViewState for such a control only wastes the resource if your application cares performance a lot?

Here we only talk about changing the value for this textbox. If we need to change it’s BackColor, for example, then viewstate is useful; or use other method to remember the changed BackColor if ViewState is not enabled.

Here is the list of controls which could be form fields meanwhile implement IpostBackDataHandler. CheckBox, DropDownList, ImageButton, ListBox, RadioButton, TextBox.

No comments: