7.10. Managing State: The Session Object

How do we correctly maintain values across posts back of a page? An HttpSessionState class object is maintained for each user that requests a page from an ASP.NET application. We store and retrieve values within this session object that we wish to persist across posts back. This object can be accessed through the page's Session property.

To initialize the values within the Session object, we need a hook into its initialization. The Session_Start() event handler provides just that hook. It is invoked once just prior to the start of a session. This is where we will insert our Anna, Pooh, and Miss count values that we increment with each appropriate user mouse click—for example,

protected void Session_Start(Object sender, EventArgs e)
{
    // OK: for curiosity's sake, let's announce ourselves ...
    Response.Write( "<B>Inside Session_Start()</B> <br>" );
    Response.Write( "<B>Session_ID: "  +
                     Session.SessionID + "</B> <br>" );

    Session.Add( "AnnaCount", 0 );
    Session.Add( "PoohCount", 0 );
    Session.Add( "MissCount", 0 );
}

Session_Start() is found inside the project-generated Global.asax.cs file. (If you don't see it, click the Show All Files icon in the Solution Explorer window. It is displayed as though it were a subdirectory of the Global.asax file.) Inside the file the project has defined a class named Global with several event handlers, including Session_Start():

public class Global : System.Web.HttpApplication { ... }

The HttpApplication class encapsulates properties common to all application objects within ASP.NET. These include the Session object, a Response object that supports transmission of HTTP response data to a client, a Request object that provides access to incoming HTTP request data, as well as a Server, a User, and an Application object.

Inside of our WebForm1 event handler, we access the Session values by a name index just as we do for a Hashtable—for example,

private void
ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    if ( e.X >= AnnaZone[0] && e.X <= AnnaZone[1] &&
         e.Y >= AnnaZone[2] && e.Y <= AnnaZone[3] )
   {
      Session[ "AnnaCount" ] =
               (int)Session[ "AnnaCount" ] + 1;

      Label5.Text = Session[ "AnnaCount" ].ToString() +
                  " Anna Hits!";
   }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.137.67