State Management in ASP.Net

State Management in ASP.NET

  • A new instance of the Web page class is created each time the page is posted to the server.
  • In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip.
  • The Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can be broadly divided into the following two categories:
     
    • Client-Side State Management Options
    • Server-Side State Management Options

Client-Side State Management

  • Client-based options involve storing information either in the page or on the client computer.
  • Some client-based state management options are:

    • Hidden fields
    • View state
    • Cookies
    • Query strings

Hidden Fields

  • A hidden field is a control similar to a TextBox control.
  • A hidden field does not render in a Web browser. A user cannot type anything into it.
  • Hidden fields can be used to store information that needs to be submitted along with the web page, but should not be displayed on the page.
  • Hidden fields can also be used to pass session information to and from forms, transparently.
  • To pass the information from one page to another, you can invoke the Server.Transfer method on the Click event of a Button control, as shown in the following example:
    1. protected void Button1_Click(object sender, EventArgs e)  
    2. {  
    3.     Server.Transfer("Page2.aspx");  
    4. }
  • The target page can access the passed information by referring to individual controls on the source page, as shown in the following example:
    1. String name = Request.Form["TextBox1"];  
    2. String color = Request.Form["HiddenField1"];  

View State

  • Each Web page and controls on the page have a property called ViewState.
  • This property is used to automatically save the values of the Web page and each control on the Web page prior to rendering the page.
  • The view state is implemented using a hidden form field called _VIEWSTATE.
  • This hidden form field is automatically created in every Web page.
  • When ASP.NET executes a Web page on the Web server, the values stored in the ViewState property of the page and controls on it are collected and formatted into a single encoded string.
  • The encoded string is:
     
    • Assigned to the Value attribute of the hidden form field, _VIEWSTATE.
    • Sent to the client as part of the Web page.
       
  • During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore the values in _VIEWSTATE.

Enabling and disabling view state

  • By default, the view state is enabled for a Web page and the controls on the Web page.
  • You can enable or disable view state for a page by setting the EnableViewState property of a Web page, as shown in the following example:
    1. <%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false" CodeFile="Page1.aspx.cs" Inherits="Page1" %> 
  • You can enable or disable view state for a control by setting its EnableViewState property to false.
  • When view state is disabled for a page, the view state for the controls on the page is automatically disabled.

Cookies

  • Cookies

    Cookies are:
     
    • Used to store small pieces of information related to a user's computer such as its IP address, browser type, operating system, and Web pages last visited.
    • Sent to a client computer along with the page output.
       
  • Types of cookies
     
    • Temporary Cookies
       
      • Exist in the memory space of a browser.
      • Also known as session cookies.
      • Are useful for storing information required for only a short time.
         
    • Persistent Cookies
       
      • Are saved as a text file in the file system of the client computer.
      • Are used when you want to store information for a longer period.
      • Are useful for storing information required for only a short time.
         
  • Creating Cookies
    1. Response.Cookies["userName"].Value = "Peter";  
    2. Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
  • Reading Cookies

    You can access the value of a cookie using the Request built-in object.
    1. if (Request.Cookies["userName"].Value != null)  
    2. {  
    3.     Label1.Text = Request.Cookies["userName"].Value;  
    4. }
Query String
  • A query string:
     
    • Provides a simple way to pass information from one page to another.
    • Is the part of a URL that appears after the question mark (?) character.
       
  • You can pass data from one page to another page in the form of a query string using the Response.Redirect method, as shown in the following example:
     

    Response.Redirect("BooksInfo.aspx?Category=fiction&Publisher=Sams");

Server-Side State Management

  • There are situations where you need to store the state information on the server side.
  •  Server-side state management enables you to manage application-related and session-related information on the server.
  • ASP.NET provides the following options to manage state at the server side:

    • Application state
    • Session state

Application State

  • ASP.NET provides application state as a means of storing application-specific information such as objects and variables.
  • The following describes the information in the application state:

    • Is stored in a key-value pair.
    • Is used to maintain data consistency between server round trips and among pages.
       
  • Application state is created the first time a user accesses any URL resource in an application.
  • After an application state is created, the application-specific information is stored in it.
     
  • Storing and Reading information in application state

    You can add application-specific information to an application state by creating variables and objects and adding them to the application state.

    For example:

    Application ["MyVariable"] = "Hello";

    You can read the value of MyVariable using the following code snippet:

    1. stringval = (string) Application["MyVariable"];

  • Removing information from application state

    You can remove an existing object or variable, such as MyVariable from an application state using the following code snippet:
    1. Application.Remove(["MyVariable"]);

    You can also remove all the application state variables and objects by using the following code snippet:

    1. Application.RemoveAll(); 

  • Synchronizing application state

    • Multiple pages within an ASP.NET web application can simultaneously access the values stored in an application state, that can result in conflicts and deadlocks.
    • To avoid such situations, the HttpApplicationState class provides two methods, Lock() and Unlock().
    • These methods allow only one thread at a time to access application state variables and objects.

Session State

  • In ASP.NET, session state is used to store session-specific information for a web application.
  • The scope of session state is limited to the current browser session.
  • Session state is structured as a key-value pair for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
  • Session state is not lost if the user revisits a Web page by using the same browser window.
  • However, session state can be lost in the following ways:
     
    • When the user closes and restarts the browser.
    • When the user accesses the same Web page in a different browser window.
    • When the session times out because of inactivity.
    • When the Session.Abandon() method is called within the Web page code.
       
  • Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID string containing American Standard Code for Information Interchange (ASCII) characters.
  • You can store objects and variables in a session state.
  • You can add a variable, MyVariable with the value HELLO in the session state using the following code snippet:
    1. Session["MyVariable"]="HELLO";
  • You can retrieve the value of the variable, MyVariable, using the following code snippet:
    1. String val = (string)Session["MyVariable"];


Similar Articles