WEBSITE

ASP.NET State Management : The View State of a Page (part 2) - Programming Web Forms Without View State

5/15/2013 1:49:56 AM

3. Programming Web Forms Without View State

By default, the view state is enabled for all server controls; however, this doesn’t mean that you strictly need it all the time and for all controls. The use of the view-state feature should be carefully monitored because it can hinder your code. View state saves you from a lot of coding and, more importantly, makes coding simpler and smarter. However, if you find you’re paying too much for this feature, drop view state altogether and reinitialize the state of the size-critical controls at every postback. In this case, disabling view state saves processing time and speeds up the download process.

Disabling View State

You can disable the view state for an entire page by using the EnableViewState attribute of the @Page directive. Although this is not generally a recommended option, you should definitely consider it for read-only pages that either don’t post back or don’t need state to be maintained.

<% @Page EnableViewState="false" %>

A better approach entails disabling the view state only for some of the controls hosted in the page. To disable it on a per-control basis, set the EnableViewState property of the control to false, as shown here:

<asp:datagrid runat="server" EnableViewState="false">
    ...
</asp:datagrid>

While developing the page, you can keep the size of the view state under control by enabling tracing on the page. The tracer doesn’t show the total amount of the view state for the page, but it lets you form a precise idea of what each control does. In Figure 1, the page contains a relatively simple DataGrid control. As you can see, the cells of the grid take up a large part of the view state. The TableCell control, in particular, strips the view state of all its user interfaces, including text, column, and row-span style attributes.

Figure 1. All controls, including child controls, contribute to the view state burden.

Note

Like all other data-bound controls, the DataGrid doesn’t store its data source in the view state. However, the data source bound to the control has some impact on the view-state size. Each constituent control in the overall data-bound user interface takes up some view state for its settings. The number of child controls (for example, rows and columns in a DataGrid) obviously depend on the data source.


Determining When to Disable View State

Let’s briefly recap what view state is all about and what you might lose if you ban it from your pages. View state represents the current state of the page and its controls just before the page is rendered to HTML. It is then serialized to a hidden field and downloaded to the client. When the page posts back, the view state—a sort of call context for the page request—is recovered from the hidden field, deserialized, and used to initialize the server controls in the page and the page itself. 

After loading the view state, the page reads client-side posted information and uses those values to override most of the settings for the server controls. Applying posted values overrides some of the settings read from the view state. You understand that in this case, and only for the properties modified by posted values, the view state represents an extra burden.

Let’s examine a typical case and suppose you have a page with a text box server control. What you expect is that when the page posts back, the text box server control is automatically assigned the value set on the client. Well, to meet this rather common requirement, you don’t need view state. Let’s consider the following page:

<% @Page language="c#" %>
<form runat="server">
    <asp:textbox runat="server" enableviewstate="false"
        id="theInput" readonly="false" text="Type here" />
    <asp:checkbox runat="server" enableviewstate="false"
         id="theCheck" text="Check me" />
    <asp:button runat="server" text="Click" onclick="OnPost" />
</form>

Apparently, the behavior of the page is stateful even if view state is disabled for a couple of controls. The reason lies in the fact that you are using two server controls—TextBox and CheckBox—whose key properties—Text and Checked—are updated according to the values set by the user. For these properties, posted values override any setting that view state might have set. As a result, as long as you’re simply interested in persisting these properties you don’t need view state at all.

Likewise, you don’t need view state for all control properties that are set at design-time in the .aspx file and are not expected to change during the session. The following code illustrates this point:

<asp:textbox runat="server" id="TextBox1" Text="Some text"
             MaxLength="20" ReadOnly="true" />

You don’t need view state to keep the Text property of a TextBox up to date; you do need view state to keep up to date, say, ReadOnly or MaxLength, as long as these properties have their values changed during the page lifetime. If the two properties are constant during the page lifetime, you don’t need view state for them either.

So when is view state really necessary?

View state is necessary whenever your page requires that accessory control properties (other than those subject to posted values) are updated during the page lifetime. In this context, “updated” means that their original value changes—either the default value or the value you assign to the property at design-time. Consider the following form:

<script runat="server">
   void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
         theInput.ReadOnly = true;
   }
</script>
<form id="form1" runat="server">
   <asp:textbox runat="server" id="theInput" text="Am I read-only?" />
   <asp:button ID="Button1" runat="server" text="Click" onclick="OnPost" />
</form>

When the page is first loaded, the text box becomes read-only. Next, you click the button to post back. If view state is enabled, the page works as expected and the text box remains read-only. If view state is disabled for the text box, the original setting for the ReadOnly property is restored—in this case, false.

In general, you can do without view state whenever the state can be deduced either from the client or from the runtime environment. In contrast, doing without view state is hard whenever state information can’t be dynamically inferred and you can’t ensure that all properties are correctly restored when the page posts back. This is exactly what view state guarantees at the cost of extra bytes when downloading and uploading. To save those bytes, you must provide an alternate approach.

Tip

You can enable and disable the view state programmatically for the page as well as individual controls by using the Boolean EnableViewState property.


Disabling the view state can also create subtler problems that are difficult to diagnose and fix, especially if you’re working with third-party controls or, in general, controls for which you have source code access. Some ASP.NET controls, in fact, might save to the view state not just properties that are officially part of the programming interface (and that can be set accordingly), but also behavioral properties that serve internal purposes and are marked as protected or even private. Unfortunately, for these controls, you do not have the option of disabling the view state. But ASP.NET 2.0 and newer versions come to the rescue with control state.

Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8