Managing State in ASP.NET

Discussion in 'ASP.NET' started by MinalS, Aug 11, 2015.

  1. To overcome this situation, there are several options added at page and application levels. In this article, we shall explore various concepts related to state management.

    Introduction to different states in ASP.NET

    There are four states used for managing states in ASP.NET application. They are as listed below:

    View State



    View state in ASP.NET provides information for the particular ASP.NET page. If there is a requirement for maintaining the web page, the .NET framework manages it automatically.

    The information about the view state is serialized into XML and encoded through base. The page performance varies if the data is large. Although the view state is enabled some of the controls do not need it. The view state can be disabled for a particular control.

    The view state for the control can be disabled by modifying the EnableViewState attribute to false.

    The view state for a web page can be modified by changing the EnableViewState attribute in the @Page directive.

    The view state for the complete application can be modified through the <pages> section in config file.

    Advantages of view state
    1. The view state values can be encoded, hashed and compressed. As a result the values are secured.
    2. There is no need to implement code for maintaining view state.
    3. There is no server resource used for managing the state
    Disadvantages of view state
    1. The data stored for view state is saved into more hidden fields on the web page. The data can be modified by the users.
    2. The performance for the web page is reduced as the values are saved in the page itself.
    3. The data storage is restricted for the memory of the device used.
    Consider the following example to demonstrate the view state in ASP.NET
    1. Add the following code in the source page of application.

      Code:
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
              EmpName:<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
              <asp:Button ID="btn1" runat="server" Text="Show" onclick="btn1_Click" />
              <asp:Button ID="btn2" runat="server" Text="Submit" />
              <br/>
              Value from Viewstate is: <asp:Label ID="lbl1" runat="server"></asp:Label>
          </div>
          </form>
      </body>
      </html>
      
      
    2. The following code is added in the code behind file.

      Code:
      
      public partial class _Default : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {
              if(ViewState["EmpName"] ! = null)
              {
                  lbl1.Text= ViewState["EmpName"].ToString();
              }
              else
                {
                  lbl1.Text = "Value not available";
              }
          }
          protected void btn1_Click(object sender, EventArgs e)
          {
              ViewState["EmpName"] = txt1.Text;
              lbl1.Text = txt1.Text;
          }
      }
      
      
    3. The code is compiled and executed and the following output is displayed.

      [​IMG]

    Session State



    The session state in ASP.NET helps user to save values. The scope of the state is restricted to current browser. Every user has a unique session id. The key/value pair structure is used for saving them.

    The SessionStateItemCollection object is used for storing the session variables. The Session property is used for exposing the object. The variables are indexed by variable name or integer index.

    Properties of HttpSessionState class are as listed below.
    1. Count: The number of items present in the session state collection
    2. CookieMode: The application is configured for the cookieless sessions
    3. IsReadOnly: State whether the session is read only
    4. Keys: The collection of keys for the values present in the session collection
    5. Timeout: The time in minutes used by the provider for ending the session
    Methods of the HttpSessionState class are listed below.
    1. Add: The new item is added to the collection
    2. Clear: All the key and values are removed from the collection
    3. GetType: The Type of the current instance is obtained
    4. RemoveAll: The key and values from the collection are removed
    5. ToString: The string representing the current object is removed
    Advantages of the Session State
    1. The events can be raised and used by the application
    2. It is consistent with the .NET framework and easy to use
    3. Customized session state can be used through the state provider
    4. The contents are kept in session state variables using the IIS.
    5. The session management events can be created by own application
    Disadvantage of the Session State

    The state variables are present in the memory till they are removed or replaced. The server performance is degraded.

    Consider the following example to demonstrate the use of session state
    1. Add the code in the source page of the application

      Code:
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
      <title></title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
          <asp:Label ID="label1" runat="server"></asp:Label>
          <br></br>
          <asp:Label ID="label2" runat="server"></asp:Label>
          <asp:TextBox ID="text1" runat="server"></asp:TextBox>
          <br/>
          <asp:Button ID="btn1" runat="server" Text="Save" onclick="btn1_Click" />
          <br/>
          <asp:HyperLink ID="hyp1" runat="server" Text="Navigate to Session" NavigateUrl="~/Default2.aspx"></asp:HyperLink>
          </div>
          </form>
      </body>
      </html>
      
      
    2. Add the following code in the code behind file.

      Code:
      
      protected void btn1_Click(object sender, EventArgs e)
      {
          Session["UserName"] = text1.Text.ToString();
          label1.Text = "Session saved";
      }
      
      
    3. Add another web page in the application. The following code is added in the source page.

      Code:
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
      <title></title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
          <asp:Label ID="label1" runat="server"><asp:Label>
          <br/>
          <asp:HyperLink ID="hyper1" runat="server" Text="GoTo Page1" NavigateUrl="~/Default.aspx"></asp:HyperLink>
          </div>
          </form>
      </body>
      </html>
      
      
    4. In the code behind file, add the following code.

      Code:
      using System;
      using System.Collection.Generic;
      using System.Linq;
      using System.Web;
      
      public partial class Default2: System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {
              label1.Text = "Welcome" + Session["UserName"];
          }
      }
      
      
    5. When the code is compiled and executed, the following output is displayed.

      [​IMG]

      [​IMG]

    Control State



    The control state data is used for monitoring the control order is working effectively. The ControlState property is used to persist the information specific to the control.

    Application State



    The HttpApplication class is used for providing the application state information. The application specific values can be saved in the application state and are managed by the server. The state is a global storage and can be accessed through the pages in the application.

    The data is present in key/value dictionary for the specific URL.

    Properties of HttpApplication state are as mentioned below.
    1. Count: The number of objects in the HttpApplication class
    2. AllKeys: The access keys are retrieved using the collection
    3. StaticObjects: The objects present in the <object> tag are accessed
    4. Item[Int32]: The single HttpApplicationState object is retrieved by the index
    5. Contents: The reference for the HttpApplicationState object
    Methods of HttpApplication state are listed below.
    1. Clear: All the objects are removed from the collection
    2. Add: A new object is added to the collection
    3. GetType: The Type of the current instance is accessed
    4. Remove: The named objects are removed from the collection
    5. Set: The value of an object is updated
    6. Lock: The variable is accessed for managing the synchronization
    7. GetHashCode: The default hash function is accessed
    The application state data are maintained using the events stated below.
    1. Application_Start: It states the start of the applciation
    2. Application_End: The end of the application is determined
    3. Application_Error: The error present in the application is mentioned
    4. Session_Start: The start of the session is specified
    5. Session_End: The end of the session is specified
    Advantages of the Application State
    1. The application state is accessed through all the web pages. A single copy can be used for storing the information
    2. It is easy for users and provides consistent framework classes.
    Disadvantages of the Application State
    1. The server memory is needed by the application state. The server performance is affected.
    2. Once the server process is destroyed, the global data of the application state is removed.
    3. The unique values cannot be saved in the application state
    There are three events provided by ASP.NET application. They are as listed below.
    1. Application_Start: It is raised when the application starts the execution. The application variables can be initialized.
    2. Application_End: When the application closes, the event is raised. All the application resources for the user are released.
    3. Application_Error: When unhandled errors occur, the exception is raised.
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice