Use Viewstate Sparingly
While the Viewstate hidden field is a great way to maintain the state of the controls in a Web Form, it comes with a performance penalty. The string stored in Viewstate grows with the number of controls on a Web Form. To see the effect of this, add a Listbox server control to a Web Form and turn tracing on. To turn tracing on in ASP.NET, switch the Web Form to HTML view and add the attribute Trace=
" to the @Page directive (see Figure 2
|Figure 2. Add the Trace="true" attribute to turn on tracing for a Web Form.|
The sample form shown in Figure 3
binds the Listbox to a DataSet containing Author names.
|Figure 3: This Web Form contains a Listbox control and a Button control.|
To display the full name of an author, a user can select the author from the ListBox and click the "Display Full Name" button. After the resulting page is loaded, you can examine the size of the Viewstate hidden field (see Figure 4
|Figure 4: The length of Viewstate grows with the number of controls in a Web Form.|
As you can see in Figure 4
, the Listbox control requires a whopping 692 bytes of Viewstate! The reason for the large Viewstate is because the control automatically attempts to retain all
the values in the Listbox. Listing 1
shows the source for this application. The page binds the Listbox to the data source the first time the user requests the page, but after each postback the page relies on the saved Viewstate to restore control settings.
The problem with a large Viewstate is that the increased length causes the Web page to be larger, which not only increases network traffic, but also results in longer processing time by the Web browser. The Viewstate is enabled by default, but there are instances where turning off Viewstate can improve the performance of your application. For instance, if there is no need to post back values (such as using the ListBox purely for displaying information), then Viewstate can be disabled. To disable Viewstate for the entire page, set the EnableViewState
attribute of the @Page
directive of the ASP.NET page to "false":
<%@ Page EnableViewState="false" Language="vb" %>
When you disable Viewstate, you may have to do extra work. In this example, every time the page is loaded, the code must bind the Listbox to the database because the values within the Listbox are no longer preserved. Also, even though the Viewstate has been disabled, ASP.NET still uses about twenty bytes for Viewstate.
Not only can you disable Viewstate at the page level, but you can also disable Viewstate at the control level. For example, the following code disables Viewstate for a ListBox control:
<asp:listbox EnableViewState="false" id="ListBox1"
You can also disable Viewstate for the entire application in the web.config