Let me clarify something first – if you think ViewState is there to repopulate your html forms, then you’re wrong. Many developers are under the impression that you should enable ViewState so that you do not have to re-assign values that a user has typed in a textbox, selected from a dropdown or checkbox. If you disable ViewState at page level by specifying EnableViewState=”false” in the page directive, you will still see the typed in value after a postback is made to the web form. Go check it for yourself! The values are restored to the controls because of the IPostBackDataHandler which they implement which basically sets their properties to the posted values.
So why do we need ViewState then?
ViewState can be helpful in situations where for example you don’t want to fetch data from your database and bypass binding altogether. This means that the first time a page is loaded, you query your database and then bind the data to a DataGrid for instance. On postback, ViewState will load the data back into the datagrid and you won’t have to do a round trip to the database server. There are also scenarios where ViewState can be a life saver but I won’t go into details about them now.
How to disable ViewState for all controls except a few ones?
If you want to disable ViewState at page level but want ViewState for a few selected controls, then you can use .NET 4 to achieve that. With earlier versions of the asp.net frameworks, you would have to loop through all the controls and enable/disable ViewState for those that you wanted because disabling it at page level would disable ViewState for every single control. However with asp.net framework 4, you can set ViewStateMode=”Disabled” on the page directive and set ViewStateMode=”Enabled” on the control that you wanted to have ViewState information. Note that you should not use EnableViewState=”false” but ViewStateMode=”Disabled” instead at the page level, otherwise no view state information will be saved.
Important things about ASP.NET ViewState
Even when you disable ViewState at the page level, you will still see the hidden viewstate field in your html because asp.net requires at least a bit of information on the control hierarchy of the page. Your page size will increase dramatically if you do not control the ViewState information. If you do not require ViewState, then turn if off (eg if you don’t need to do postbacks). Increase in page size because of view state means longer time to render the page and slower response time from server because it needs to save view state information as well. For fast loading pages, use view state on controls which need it.
You can also save view state information somewhere else rather than in the html being rendered. There’s a bit of serialisation to do and cleanup afterwards but it can be done.
For more information, please refer to http://msdn.microsoft.com/en-us/library/ms972976.aspx