Share This!

Saturday, May 24, 2014


I have heard it a thousand times.  Web pages are stateless.  That means that - unlike desktop apps where you load a form with data and it stays loaded as long as the app is running - a web page loads. renders, and the webserver immediately forgets everything.

At least that's the way it was.

In the bad old days, web designers would put hidden fields on the form, and hide data there, sometimes raw data, and sometimes just a handle to session data being stored on the webserver, or in a database.

But these days, our frameworks have built-in storage for state information, and some components save their state data by default. Note the differences:

Create an HTML form (even in an ASP.NET site) and put this code in it.

<!DOCTYPE html>
<html xmlns="">
    <form id="thisform" action="HtmlPage.html" method="get">
        <input id="Text1" type="text" />
        <input id="Button1" type="submit" value="Post" />

This is the oldschool way of doing form posts.  Note that if you click the submit button, the text you put in the text box will disappear.  That's because it's state (value) is not being stored.  Now create an form.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" />

Note that this example remembers the values typed in its boxes on a postback.  Now, in the browser, do a view page source.

Notice that there is a line in there that looks like this:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="E+wH9na5ksRkcpEtk56HJ50O8S2k8vu5dqruZeQtCdLxTdF9WHAcmxUsqAeaxzlLld9hLgv6LIwp+KFpLzzJEdyW2AOL2gz/b2NZ2SOhfx0=" />
That's the automatic way ASP.NET stores state information on the web page.  If you pick the textbox and look at its properties, you'll notice one called EnableViewstate and another called ViewstateMode.  Saving state is enabled by default.

So this gets us to the two ways to store state information on an ASP.NET page.
  • Viewstate
  • Session


As discussed, viewstate stores the status of all viewstate-enabled controls.  But you can also add stuff to Viewstate, and read it out again, even complex objects.
            //add a key
            ViewState.Add("myKey", "myValue");

            //store complex objects
            DataSet myData = new DataSet();
            ViewState.Add("data", myData);

            //change a key
            ViewState["myKey"] = "myNewValue";

            //read a key
            string data = (string)ViewState["myKey"];

            //delete a key

Note the following:
  1. ViewState lives in the page.  It does not flow from page to page. 
  2. Multiple users (like different computers and even 2 different browsers on the same computer do not share ViewState).
  3. ViewState is only read on a POSTBACK, not on an initial load of the page.
  4. I have found that storing things in ViewState can result in hard-to-debug errors that make your development life a living hell.
learn more


Session is like ViewState, in that it is created automatically whether you want it or not. Session is linked to the user, not the page.  When someone browses to your page and there is no session ID, a new session is created.  Some features of sessions are:
  • Sessions time out after a period of inactivity.
  • Session data persists for that user until the session times out
  • Sessions can store complex items like ViewState
  • Sessions are unique, not shared if more than one browser is opened
Using sessions is easy, and since regular objects do not do anything with sessions, it's not likely to get you trapped into the impossible-to-diagnose error loop you get with ViewState.

            //add a key
            Session.Add("myKey", "myValue");

            //store complex objects
            DataSet mySessionData = new DataSet();
            Session.Add("data", mySessionData);

            //change a key
            Session["myKey"] = "myNewValue";

            //read a key
            string data2 = (string)Session["myKey"];

            //delete a key

            //Special session methods
            if (Session.IsNewSession) { }
            string s = Session.SessionID;

Take care when using sessions. Note that the values are available to all pages on the site.  For instance, let's say you put a SortedBy value in multiple pages.  If the user travels from Customers sorted by LastName to the Orders page, the "SortedBy" key still says "LastName".
learn more


Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Contact Us


Email *

Message *