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 (attached) 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.

Julian. 

Comments

What I’m excited about - Agile goodness of DDD/TDD/ORM etc.

I have spent a lot of time resarching the internet (and in particular other people blogs) for information on my specific agile topics of interest:

With all that great info out there, I thought it wouldn’t hurt to have another filtered view of the world.  So I will be following up with some articles on my own.

Stay tuned,

Julian.

Comments