ASP.NET and ViewState

The previous article, ASP.NET and HTML introduced the relationship between ASP.NET Server Controls and the HTML controls they render. When we examined the HTML code listing, we saw that ASP.NET creates a hidden form variable, _VIEWSTATE. This article explains the ASP.NET ViewState mechanism.

Another Look

To demonstrate the relationship between ASP.NET and HTML, we built a simple application, containing a label, a textbox, and a button. We used the default properties, and added no extra code (see Figure1).


When we run the application, and view the HTML it creates in Internet Explorer, we can see the hidden form element named "_VIEWSTATE".

Example 1. HTML code listing.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema"
    content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>

<body MS_POSITIONING="GridLayout">
  <form name="Form1" method="post" action="WebForm1.aspx" id="Form1">

    <input type="hidden" name="__VIEWSTATE"
    value="dDw2NjAyODY5ODQ7Oz5e7BRSozIDiro7YlZj+Hgc+FXhbQ==" />

    <input name="TextBox1" type="text" id="TextBox1"
    style="Z-INDEX: 101; LEFT: 96px; POSITION: absolute; TOP: 32px" />

    <span id="Label1" style="Z-INDEX: 102; LEFT: 40px;
    POSITION: absolute; TOP: 32px">Label</span>

    <input type="submit" name="Button1" value="Button" id="Button1"
    style="Z-INDEX: 103; LEFT: 192px; POSITION: absolute; TOP: 72px" />

  </form>
</body>
</HTML>

ASP.NET and Form Elements

The ASP.NET ViewState is often erroneously described as the mechanism which "saves" form data. Even the w3school's article on ViewState makes this misstatement: "When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState." With all due respect, that isn't the case.

While it's true that ASP.NET automatically repopulates form values, that is not part of the ViewState mechanism! HTML form elements post their current values from the browser to the server in the HTTP header. ASP.NET uses the data in the header to repopulate the form on postback. That is a major timesaver, but it is NOT accomplished via ViewState.

We can test this quite easily. Just disable the viewstate for our sample application. You can do this in HTML view by adding enableViewState="false" in the Page Directive.

Example 2. Disabling ViewState.
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
  Inherits="testsuite.WebForm1" enableViewState="False"%>

You can also set the property, in Design View, in the DOCUMENT's property page. When you run the application, fill out the form, and click "submit", you'll see that the page comes back with the previous form values intact, even though ViewState is disabled.

Note: if you View Source, you may still see a hidden _VIEWSTATE form element. This is because ASP.NET maintains the state of the Page itself. If you're not quite trusting me on this (I doubted it myself), then disable the viewstate of the textbox control itself. Any value entered will still persist through a postback.

So, whatever ViewState is, we can state that it is NOT used to persist form values between postbacks.

Okay, You're Right - But I Still Don't Know What ViewState IS

ViewState is used to store values that are NOT automatically included in the HTTP Headers. Want an example? I thought so: look again at our Label in the HTML code listing. This control started out as an ASP.NET Server Control, a "Label". It is rendered as an HTML "span" element. While that works perfectly well, "spans" are not inputs. When the user submits the form, the content of the span is NOT submitted. It's no problem, if the value of the label never changes. But what if it does?

It is typical in an ASP.NET application to set properties of controls the first time the page loads. Let's change our label text from "Label" to "TEST" in our code-behind file:

Example 1. HTML code listing.
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!IsPostBack)
	{
		Label1.Text = "TEST";
	}
}

The first time the page loads, we override the default setting of the Label control, changing the Label1.Text property from "Label" to "TEXT". If we submit the page, what happens? If you still have ViewState disabled, you'll see the value change back to "Label". With ViewState enabled, however, we keep the value of "TEXT". This is a simplistic example, but it nicely demonstrates the ViewState mechanism.

Consider the range of ASP.NET Server Controls, and the fact that they all render to HTML. For HTML form elements, ASP.NET uses the data in the HTTP Headers to restore values. For all other elements, ASP.NET uses ViewState to persist any changes we may make in server-side code.

The web is inherently stateless. When we make server-side changes, ASP.NET will dutifully render the new HTML to the browser. But it then immediately forgets all about it. The user may NEVER come back. If they do, how will the application "remember" our new values and properties? ASP.NET solves this by bundling all the changes we made to our controls into the hidden form variable, _VIEWSTATE, which it adds to the page. When the user re-submits the page, ASP.NET uses the data in the _VIEWSTATE variable to restore the state of our server controls.

It Looks Funny

So would you, if you were base64 encoded text. The actual format of the ViewState value is beyond the scope of this document. But you should note, that it is ENCODED, not ENCRYPTED. If you feel that you need a more secure ViewState value, you should search MSDN for articles on the "EnableViewStateMAC" attribute, which generates a hashcode for the ViewState. You can also encrypt the ViewState value by adding a validation key to your machine.config file: <machineKey validation="3DES" />.

Conclusion

While often misunderstood, ViewState is not mysterious. It is a simple way for ASP.NET to retain changes we make programmatically to the properties of our ASP.NET Server Controls, by packaging them as a hidden form variable. This is in fact a very old trick in web development.

About the Author

Thomas D. Greer has years of experience in the printing business. He held the position of Director of Development for Consolidated Graphics, where he wrote the COIN eCommerce platform. Prior to that he was Vice-President of Technology of a large printing company acquired by Consolidated Graphics, where he was responsible for the development of a completely custom-written plant management system still in use.

Today Thomas provides consulting, development, implementation, and training services to commercial printers. He can be reached on the web at www.tgreer.com.

Now What?

Perhaps you'd like to read some other technical articles I've written?

If you'd like to discuss this article, or make suggestions for future articles, join my free discussion forum.