Tuesday, January 16, 2007

ASP.NEt 2.0 Viewstate and good practices

View state is one of the most important features of ASP.NET because it enables stateful programming over a stateless protocol such as HTTP. Used without strict

criteria, though, the view state can easily become a burden for pages. Since view state is packed with the page, it increases size of HTTP response and request.

Fortunately the overall size of the __VIEWSTATE hidden field (in ASP.NET 2.0) in most cases is as small as half the size of the corresponding field in ASP.NET 1.x.The content of the _VIEWSTATE field (in client side) represent the state of the page when it was last processed on the server. Although sent to the client, the view state doesn't

contain any information that should be consumed by the client.

In ASP.NET 1.x, if you disable view state of controls, some of them are unable to raise events hence control become unusable. When we bind data to a grid, server encodes and put whole grid in to view state, which will increase size of view state (proportional to the data volume of grid). We cannot disable view state, if we need features like pagination, edit, and sorting.

But in ASP.NET 2.0 view state can be disabled more freely. Because controls keep contents required for their behavior in control state. View state is purely to maintain control’s UI content. Following simple guidelines can be used to handle view state appropriately.

* Use page’s view state when data elements are required to persist between requests. E.g. ViewState("DataElement") = someDataElement

You can disable page view state by setting EnableViewState="false" in page directive of aspx.

* Do not use page’s view state to persist control’s data. Enable control’s view state, so data will be available between requests. E.g. data source of a Dropdown list

* If you populate the contents of a control (from some data source) every time a page is requested, it is generally safe (and wise) to disable view state for that control. E.g. EnableViewState="false"

MultiView, Table, etc.. keep control state, hence view state can be disabled without affecting events.)

* If you don’t want to populate contents, you can declaratively place a data source on your page and point your control to that data source with view state enabled. Above controls exhibit intelligent use

of view state when bound to declarative data sources. So there wont be any hit to backend data source in post backs.

As a refactoring tip, disable view state at page level and check when and where it breaks. If functionality breaks, verify that you have used page view state correctly.

If you have used it properly, enable view state at page level and disable at each and every control level by considering above best practices