There's no doubt about it, the fact that ASP.NET handles ViewState for us
is a godsend. Just ask anyone who has spent time developing in classic
ASP and they'll probably shudder at the thought of all the time and effort
they wasted managing state. That being said, this magic that ASP.NET
give us does come at a cost. The cost is larger web pages... sometimes surprisingly large.
ASP.NET maintains a page's ViewState by using hidden form fields that look something like this:
Most of the time, this solution works amazingly well.
The small increase in page size is normally not even noticed and the slight
extra bandwith used is well worth the benefits we gain.
The problem comes when you have a page which uses a large number of server controls.
The more controls on the page, the more ViewState needs to be stored.
The question then becomes: "Do we really need all this ViewState?"
Well that depends... but often you don't.
For example, many pages that simply display data in a DataGrid or GridView don't
need ViewState. Same goes for any page that doesn't postback to the server or
resets its controls each time it's requested. In these scenarios, you're paying
the price for functionality you're not even using.
So what can we do? Well that's easy... simply disable ViewState where it's not needed.
You can control ViewState at either the page and control level. If an entire page doesn't
need it, simply set the page's EnableViewState attribute to false.
If parts of the page use ViewState, you can still disable it for the controls that don't need it.
For example, if you've got a reporting page that contains a query form that returns read only data
in a GridView, you can still use ViewState to maintain the form values, even if you turn it off
for the GridView control.