Monday, August 20, 2007

All about Control State

I mentioned earlier that one of the most frustrating aspects of working with server-side controls in ASP.NET 1.x is the all-or-nothing mentality with respect to view state. Behavioral aspects of controls like pagination in the DataGrid or selection change notifications in textboxes require view state to be enabled to function properly. I'm sure all of you are sufficiently daunted by the prospect of leaving view state enabled in any of your DataGrids at this point.
In ASP.NET 2.0, Microsoft addresses this particular problem by partitioning the view state into two separate and distinct categories: view state and control state.

Control state is another type of hidden state reserved exclusively for controls to maintain their core behavioral functionality, whereas view state only contains state to maintain the control's contents (UI). Technically, control state is stored in the same hidden field as view state (being just another leaf node at the end of the view state hierarchy), but if you disable view state on a particular control, or on an entire page, the control state is still propagated. The nice aspect of this implementation is that we can now amend our original principle on optimizing view state for ASP.NET 2.0 to be much stronger: if you populate the contents of a control every time a page is requested, you should disable view state for that control.

NOTE for Control State Users

For those of you building controls, the usage model for control state is not quite as convenient as view state. Instead of providing a state-bag with an indexer to insert and remove items, you must override the virtual LoadControlState and SaveControlState methods and manually manage your portion of the object collection that is mapped into control state. The one other thing you must do is call the Page.RegisterRequiresControlState method during initialization so that the page knows to ask for control state at the right time.
It is probably a good thing that storing items in control state is more difficult than view state since there is no way for users to disable it (there are also performance advantages to having an opt-in model for control state). Developers should think carefully before storing any state there as it will always be added to the rendering of a page.

No comments: