Microsoft created ASP.NET ViewState to help alleviate
the difficulties of programming in the Web’s stateless environment. But like
every tool that makes a developer’s life easy, it comes with a price:
performance. In the case of ASP.NET ViewState, the performance problem
results from the increased size of any page that uses ViewState.

ViewState basics

ViewState works by adding hidden input fields to the
Response, which helps maintain the state of objects in the page. But on high-volume
Web sites where every byte of network bandwidth counts, you may want to limit
the ViewState size—especially when you consider that ViewState is not only
sent out to the client but also gets sent back to the server with each request.
In essence, every byte added to a page by ViewState causes two bytes of
network traffic, one in each direction.

ViewState is enabled on four levels: machine,
application, page, and control. The machine and application levels are
controlled by configuration file settings, while the page and control ViewState
settings are controlled by properties. Most sites that use ASP.NET will use
ViewState in at least portions of the site, so turning it off at the machine
or application level often is not feasible. Therefore, ViewState must be
handled carefully at the page and control levels.

Eliminating bytes

To maximize performance, each page should be judged on
whether it needs ViewState information. If no ViewState is needed in the page
or any of its controls, set the EnableViewState property of the page or control
to false. Also, remove the runat=”Server”
attribute from the form tag. If this tag isn’t removed, the page itself passes
on about 20 bytes of information to the ViewState.

If ViewState is needed, make sure it is enabled only for controls
that are really going to use it. Some controls, such as Label and TextBox,
do not have a large ViewState footprint. But DataGrids and DataRepeaters store
all of their data in ViewState by default, making the page’s output potentially
very large.

If you want to use one of these larger footprint controls,
you can reduce its size by setting the EnableViewState property to false. This
will force the DataGrid to go to the datasource for its data with each request,
which of course impacts whatever datasource you’re using. But it will greatly
reduce the size of the HTML stream sent to the client.