24. May 2007 08:49
It seems one of the more complicated aspects of ASP.Net for many developers is understanding ViewState. There are many misconceptions about what it does for you, and what it does not do.
What ViewState is Not
ViewState does not restore user posted values to form controls. ASP.Net does this for us, but it has nothing to do with ViewState.
If the user posts a value to a control, checking a checkbox for instance, and a postback occurs, ASP.Net will restore this value for you in the 'ProcessPostData' method, which occurs before AND after the OnLoad event. It happens twice, so that if you were to dynamically create your control in the OnLoad event, it's value would still be restored, although that value would NOT be available until AFTER the onload event was complete.
While this is very helpful to the developer, it has nothing to do with ViewState.
ViewState also will not restore any controls that you generated dynamically. So if you put a !IsPostBack around your dynamically generated controls, they won't be there when the page posts back.
What ViewState IS
ViewState records the properties that are dynamically changed in your code, whether explicitly, or via data-binding, such that they can be restored on each request.
If you create a textbox in your pages OnInit method, and in OnLoad set the value of the textbox while !PostBack, the value will still be persisted on postback.
After the OnInit method completes, and all controls that may need their ViewState restored already exist, the "LoadPageStateFromPersistanceMedium" method executes and repopulates the value of your textbox.
Keep in mind that if a user had added text to the textbox before posting back, that this too would be available OnLoad, but not due to ViewState, instead due to the 'ProcessPostData' event.