Practical example for ViewState

There have been considerable improvements in the way ViewState is serialized with ASP.NET 2, and with the added ControlState functionality it is possible for third party controls to behave themselves with ViewState disabled.

There are some great articles written on understanding ViewState like this one by Scott Mitchell. My practical example (see below) list some ways to minimizing view state.

My example utilises a custom TextBox control that raises events when it’s value has changed, or had saved its ViewState. In addition I persist the number of times it has ‘Changed’ to illustrate the key point:

  • A control with ViewState disabled will still fire its Change event if the posted-back value has changed when compared with its initialized value.

Developers often DataBind ListItem controls if (!PostBack) on Page_Load, however this results in the ViewState bloat. An alternative is to always DataBind on Page_Init, this is particularily useful for reference data that doesn’t change often and is ‘cheap’ to load:

  • A control DataBound in Page_Init routine it will still receive it’s PostBack event and post data without requiring ViewState.

Please see my View State Example project for more details.