ASP 101 - Active Server Pages 101 - Web01
The Place ASP Developers Go!

Windows Technology Windows Technology
15 Seconds
ASP 101
ASP Wire
VB Forums
VB Wire
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an site
ASP 101 is an site
Internet News
Small Business
Personal Technology

Corporate Info
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash

 Top ASP 101 Stories Top ASP 101 Stories
Getting Scripts to Run on a Schedule
The Top 10 ASP Links @
What is and Why Do I Need It?

Use Descriptive Naming Of Files And Directories
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates

Form Viewstate

by John Peterson


Up till now, it's been pretty easy to decide what topic I should cover next as I've been writing these lessons. This week the choice was a little more difficult. You see I want to get you into some of the really cool stuff, but I don't want to get you lost along the way. This week's topic is not exciting, flashy, or sexy, and as a result, it's something that most books and web sites I've seen have sort of glossed over. Well that's really too bad, because it's an important topic to understand and for many users (especially those transitioning from previous versions of ASP), it's probably the feature that will save them the most coding. I'm talking about maintaining the viewstate of the objects on your web pages (or as their now being called Web Forms).

What Is Viewstate?

It's probably easiest to explain with an example. Let's say you're about to buy something online. You've filled out your name, address, payment info, and given these people, whom you've never met, information you normally wouldn't share with your closest friends (but that's another rant altogether). You submit the form and the server comes back saying there's an error and you need to go back and add -'s to your phone number or some other petty little thing. You click the back button in your browser and you stare at the screen in dread as you realize all the entries you typed are now gone and you have to start all over! The site in question didn't maintain your viewstate.

A couple years ago nobody noticed this type of thing, but nowadays if your site's usability isn't up to snuff, people will simply go somewhere else. So instead of telling people to go back and fix their information, somewhere along the line, we all sort of unconsiously decided it would be easier just to send them back to the form automatically and have all the information they entered there waiting for them to fix. This is where the headache came in for the developer. Now we not only had to build the form (and make it pretty to make the designers happy), we also had to have the form be able to maintain the data from request to request. While it's not really all that difficult, it can be really annoying to code, and is generally a pain in the @$$ for a feature that no one even appreciates anymore.

And it's not just e-commerce sites. Basically anywhere there's a form, people expect you to fill it in for them if it's at all possible. While ASP.NET doesn't fix all of this... you'll still need to pull values from the DB for first requests and stuff like that, it does make keeping track of the state of things while the user is filling out the form much easier. Let me show you.

Our Baseline Form

Here's a basic form. It doesn't do much. It takes a name and you select a color from the drop down list. With these values the page builds a little sentence. What do you want... it's for illustation and we haven't covered databases yet. If it helps make the example less trivial, you can think of the entries as database query parameters and the sentence as the resulting query string.

<%@ Page Language="VB" %>
<script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
        If Request.Form("txtName") <> "" Then
            lblSentence.Text = Request.Form("txtName") _
                & " selected " & Request.Form("ddlColor")
        End If
    End Sub
<title>ASP.NET Viewstate Form Sample #1</title>
<body bgcolor="#FFFFFF">
<form action="form1.aspx" method="post">
    Enter Your Name:
    <input type="text" id="txtName" name="txtName" />
    Pick a Color:
    <select id="ddlColor" name="ddlColor">
    <input type="submit" id="btnSubmit" text="Submit" />
<asp:label id="lblSentence" runat="server" />

Give it a whirl... it works, but after each submission the form resets to no name and the color goes back to red. That's fine, but compare it to the next listing.

Once More... With Viewstate

Now that you've seen the old way... here's the new ASP.NET way.

<%@ Page Language="VB" %>
<script runat="server">
    Sub btnSubmit_Click(Sender As Object, E As EventArgs)
        lblSentence.Text = txtName.Text & " selected " _
            & ddlColor.SelectedItem.Text
    End Sub
<title>ASP.NET Viewstate Form Sample #2</title>
<body bgcolor="#FFFFFF">
<form id="frmViewState" action="form1.aspx"
    method="post" runat="server">
    Enter Your Name:
    <asp:TextBox id="txtName" runat="server" />
    Pick a Color:
    <asp:DropDownList id="ddlColor" runat="server">
    <asp:button id="btnSubmit" text="Submit"
        onClick="btnSubmit_Click" runat="server" />
<asp:label id="lblSentence" runat="server" />

This time when you submit, the form keeps it's values from run to run. The next thing I want you to notice is that the two code listings are almost exactly the same length. In the second it's the ASP.NET framework that's doing all the work for us. From a development point of view, it makes trips to the server almost transparent. You code off the press of a button or the entry of text in a texbox and ASP.NET worries about the little things and adjusts the communication with the client accordingly.

How Does It Perform This Magic?

Basically there are two main parts to the magic. The first is the client detection and dynamic adjustment of the HTML (or whatever) being sent to the client. A perfect example is the calendar control we played with last week. On high-level browsers the control sends some of the code to manipulate itself as javascript. If the client can't handle this code, the server doesn't send it and makes a roundtrip to the server each time a date is selected. The point being... the code you wrote didn't change... the control took care of it.

The second magic wand in the magic box is the one that handles the viewstate. Basically most controls maintain their state via hidden form fields. If you do a View Source in your browser while viewing the second form, you'll see a line that looks something like this:

<input type="hidden" name="__VIEWSTATE" value="dDwtMTA2Mzk5MTczNDt0PDtsPGk8Mz47PjtsPHQ8cDxwPGw8VGV4dDs+ O2w8Sm9obiBzZWxlY3RlZCBHcmVlbjs+Pjs+Ozs+Oz4+Oz6NaBGW1O3JUoxq0PX rlih3OZ2CTA==" />

I added the line breaks simply to keep things readable.

In essence the server is sending the state of the form along with the form each time it's sent back to the client in the form of this hidden field (pardon the pun). It's important to note that this is not stored on the server and it's not done via ActiveX controls or a Java applet or any type of client-side trick. The state is maintained via standard HTML and the only real downside I can see is the increase in the size of the page and the resulting next get request... a small price to pay if you ask me. If even that price is too high for you, you can (and should) disable viewstate where it's not needed.

To illustrate this, I've disabled viewstate on all but the two controls that use it by adding the EnableViewState="false" attribute. I've included the modified file, named form3.aspx, in the zip file. If you look at the hidden viewstate field of this form after making a request, you'll notice that it's much smaller then the viewstate from form2.aspx.

Download The Samples

That just about covers viewstate. As always, we've got all the code from this lesson in a nice neat zip file for you. Now that that's out of the way, I promise the next lesson will be a little more exciting... or on second thought... I'm still writing it so maybe not...   ;)

Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback
The Network for Technology Professionals



Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers