Sunday, May 17, 2009

Why should you avoid the excessive use of ViewState in Asp.Net web page?

Automatic state management is a feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field.

Since the view state data resides in a hidden form field (__VIEWSTATE); ViewState increases the size of page and results in slow loading of page at browser. You should be aware of when ViewState is helping you and when it is not.

For example, if you are binding a control to data on every round trip , then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false, as in the following example:
< asp:datagrid EnableViewState="false" datasource="..." runat="server"/>
You can also turn ViewState off at the page level. This is useful when you do not post back from a page at all, as in the following example:
< %@ Page EnableViewState="false" %>
Note that this attribute is also supported by the User Control directive.

No comments:

Post a Comment