State Management Concept In ASP.NET

State management is very important and useful in ASP.NET. It is also asked in many interviews to fresher and experienced developers.

State management is a preserve state control and object in an application because ASP.NET web applications are stateless. A new instance of the Web page class is created each time the page is posted to the server. If a user enters information into a web application, that information would be lost in the round trip from the browser (MSDN).

In a single line, State management maintains and stores the information of any user till the end of the user session.

Two Types of State Management techniques are available in ASP.NET as in the following figure,

State management
Figure 1: State Management Part

Server side

  1. Session

    Session is a very important technique to maintain state. Normally session is used to store information and identity. The server stores information using Sessionid.

    Set User Session:
    1. protected void btnSubmit_Click(object sender, EventArgs e)  
    2. {  
    3.    Session["UserName"] = txtName.Text;  
    4.   
    5.    Response.Redirect("Home.aspx");  
    6. }  
    Session Event:

    Session event can be seen in project Global.asax file.

    Two types of Session Events

    1. Session_Start

      The Session_start event is raised every time a new user requests without a session ID.
      1. void Session_Start(object sender, EventArgs e)  
      2. {  
      3.    Session["master"] = "~/Master.master";  
      4. }  
    2. Session_End

      The Session_End event is raised when session is ended by a user or a time out using Session end method.
      1. void Session_End(object sender, EventArgs e)  
      2. {  
      3.    Response.Write("Session_End");  
      4. }  
      The session is stored in the following for ways in ASP.NET.

      • InProcMode:

        It is a default session mode and a value store in web server memory (IIS). In this the session value stored with server start and it ends when the server is restarted.

      • State Server Mode:

        In this mode session data is stored in separate server.

      • SQL Server Mode:

        In this session is stored in the database. It is a secure mode.

      • Custom Mode:

        Generally under session data is stored in InProc, Sql Server, State server, etc. If you store session data with other new techniques then provide ASP.NET.
  2. Application

    Application State is a server side management state. It is also called application level state management. In this mainly store user activity in server memory and application event shown in Global.asax file.

    Their are three types of applications in ASP.NET.

    1. Application_Start:

      This event Start with domain start.
      1. Void Application_Start(object sender, EventArgs e)  
      2. {  
      3.    Application["AppstartMessage"] = "Welcome to CSharp Corner Developer Communtiy";  
      4. }  
    2. Application_Error:

      In this section manage unhandled exception error.
      1. void Application_Error(object sender, EventArgs e)   
      2. {   
      3.    // Write an unhandled error code exception  
      4. }  
    3. Application_ End:

      This ends with domain or restarts IIS.
      1. Void Application_End(object sender, EventArgs e)  
      2. {  
      3.    Application["AppEndMessage"] = "Application Closed";  
      4. }  
  3. Cache

    Cache is stored on server side. It implements Page Caching and data caching. Cache is use to set expiration polices

    Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));

Client Side

Now here I am explaining client side state management one by one:

Also state management has the following four important parts available on the client side:

  1. Cookie

    Cookie is a small and an important part of ASP.NET. In this store user information, session and application. It can be created constant and temporary and they work with browser request. Cookies are store on client side. The server can read cookies and abstract data.

    Two types of cookies are available,

    1. Persistence

      This type of cookie works with Date and time.
      1. Response.Cookies["CookieName"].Value = "Test Cookies";  
      2. //set expire time   
      3. Response.Cookies["CookieName"].Expires = DateTime.Today.AddHours(1);  
    2. Non-Persistence

      This is a temporary cookie. It is created with access application and discards the close application.
      1. Response.Cookies["CookieName"].Value = "Test Cookies";  
  2. Control state

    Control state technique is developed to maintain data work properly in order. We can use view state but suppose view state is disabled by the user, the control will not work as expected. For expected results of the control we have to use Control State. In application, the Viewstate is by default true. Sometimes we need to use custom control to manage application properly.
    1. if (!IsPostBack)  
    2. {  
    3.    lblmsg1.Text = "Welcome to C# corner";  
    4.    lblmsg2.Text = "Welcome to C# corner community";  
    5. }   
    When two messages are displayed on a Postback event, then control which one is displayed by using customized control state.

  3. Hidden Field

    Hidden fields are used to store value to client side. Hidden field is not displayed on the browser, but it works on a request.
    1. if (HiddenField1.Value != null)  
    2. {  
    3.    int val = Convert.ToInt32(HiddenField1.Value) + 1;  
    4.    HiddenField1.Value = val.ToString();  
    5.    Label1.Text = val.ToString();  
    6. }  
  4. Viewstate

    Viewstate is a very useful client side property. It is used for page level state management. Viewstate stores any type of data and used for sending and receiving information,

    Example 1: Count.
    1. ViewState Demo Count: <asp:Label runat="server" id="lblcount" />  
    2.   
    3. <asp:Button runat="server" id="Submit" onclick="Submit_Click" text="show" />   
    4.   
    5. protected void Page_Load(object sender, EventArgs e)  
    6. {  
    7.     if (IsPostBack)  
    8.     {  
    9.         if (ViewState["count"] != null)  
    10.         {  
    11.             int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;  
    12.             lblcount.Text = ViewstateVal.ToString();  
    13.             ViewState["count"] = ViewstateVal.ToString();  
    14.         }  
    15.         else  
    16.         {  
    17.             ViewState["count"] = "1";  
    18.         }  
    19.     }  
    20. }  
    21. protected void Submit_Click(object sender, EventArgs e)  
    22. {  
    23.     lblcount.Text = ViewState["count"].ToString();  
    Example 2: Set/Get user.
    1. if (ViewState["UserName"] != null)  
    2. lblName.Text = ViewState["UserName"].ToString();  
    OR
    1. ViewState["UserName"] = txtUserName.Text;  
    Viewstate is easy to apply and do not need to any server resources. In a Viewstate, do not store big data, only store small values. Viewstate enables and disables on page level control. It also supports Encryption and Decryption and data/value is stored in hashed format. So we are not storing important data such as password, account information, etc. When more data is stored in this, then the page becomes heavy. 

  5. Query String

    Query string stores the value in URL.

    Response.Redirect("ShowStringValue.aspx?Username=" + txtUsername.Text);

    It is visible to all the users in url as in the following link: 

    output

I hope you enjoyed the clear state management concept in ASP.NET.

Next Recommended Readings