How to Work with State Management in ASP.Net

 

HTTP is a stateless protocol, actually, statelessness is one of the many advantages of the WWW. In a statelessness condition, all information associated with the page and the controls on the page would be lost with each request from a user to Web Server and response from the Web server to a user. There is no standard way in which the server can determine whether a subsequent HTTP request is from the same user.

To overcome this limitation, ASP.NET includes several features that help you preserve data on both sides (client side, server side) by its State Management Capabilities.

In this Blog, I give an overview of state management techniques in ASP.NET. I will be discussing the various types of state management techniques in ASP.NET both the sides (client side and server side).

State management

All ASP.NET web applications are stateless. By default, when a page posted to the server then the state of controls is lost. So State management is used to preserve the state of a control, web page, object/data, and user in the application explicitly.

Types of state management

There are two types of state management techniques: client side and server side.

Client side

  1. Hidden Field
  2. View State
  3. Cookies
  4. Control State
  5. Query Strings

Server side

  1. Session
  2. Application

Levels of state management

  1. Control level: by default controls provide state management automatically in ASP.NET.
  2. Variable or object level: Member variables at page level are stateless and thus we need to maintain the state of member variables explicitly in ASP.NET.
  3. Single or multiple page level: managing state between page requests i.e. multiple page levels as well as single page level.
  4. User level: managing state as long as a user is running the application.
  5. Application level: State Management for complete application irrespective of the user and it should be available to all users.
  6. Application to application level: managing State between or among two or more applications.

Client-side State management

Client Side State Management information is stored either on a Web page or on a Client computer rather than using the web server’s memory. There are four ways to manage states.

Client-side State management Techniques:

1. Hidden field

Hidden fields are used to store a small amount of data on the client side. It stores one value for the variable and it is a preferable way when a variable’s value is changed frequently.ViewState stores information in the Web page using hidden fields and sent back to the server when the user submits a form; however, the information is never displayed by the Web browser (unless the user chooses to view the page source).In ASP.NET we can create your own custom hidden fields and store values that are submitted with other form data.

Example:

Let us see with a simple example how to use a hidden field. These examples increase a value by 1 on every “Submit Button” click. The source of the hidden field control is.

<asp:HiddenField ID="HiddenField1" runat="server"  />

In the code-behind page:

protected void Page_Load(object sender, EventArgs e)
{
   if (HiddenField1.Value != null)
   {
    int val= Convert.ToInt32(HiddenField1.Value) + 1;
    HiddenField1.Value = val.ToString();
    Label1.Text = val.ToString();
   }
}
protected void Button1_Click(object sender, EventArgs e)
{
  //this is Submit Button Click
}

 

2. View state

View State is mainly used to preserve data temporarily after post back. It stores data in the generated HTML using the hidden field, not on the server.it provides page-level state management i.e. it stores state as long as the user is on the current page and the user redirects to another page, the current page state is lost. View State is object type so it can store any type of data but it is not preferable to store a complex type of data due to the need for serialization and deserialization on each post back. It is enabled by default for all server-side controls of ASP.NET with a property EnableviewState set to true.

Example:

In the example, we try to save the number of postbacks on button click.

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

So the above example clear how to use view state.

3.Cookies

cookies are used to store small pieces of data in the client’s Web browser by the web application. it stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary).

Whenever first time a user makes a request for a page then server creates a cookie and sends it to the client browser along with the requested page and stores it on the client machine. The next time the user makes a request for the same site for any page then the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, otherwise, that request is treated as a new request.cookies are mainly used to identify a single user as he or she visits multiple Web pages.

Example:

Let’s see how to check for a cookie named DateCookie in the HttpRequest object. If the cookie is not found, it is created and added to the HttpResponse object. The cookie expires within 5 minutes.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        // Get cookie from the current request.
        HttpCookie cookie = Request.Cookies.Get("DateCookie");

        // Check if cookie exists in the current request.
        if (cookie == null)
        {
            sb.Append("Cookie was not received from the client. ");
            sb.Append("Creating cookie to add to the response. ");
            // Create cookie.
            cookie = new HttpCookie("DateCookie");
            // Set value of cookie to current date time.
            cookie.Value = DateTime.Now.ToString();
            // Set cookie to expire in 5 minutes.
            cookie.Expires = DateTime.Now.AddMinutes(5d);
            // Insert the cookie in the current HttpResponse.
            Response.Cookies.Add(cookie);
        }
        else
        {
            sb.Append("Cookie retrieved from client. ");
            sb.Append("Cookie Name: " + cookie.Name + "");
            sb.Append("Cookie Value: " + cookie.Value + "");
            sb.Append("Cookie Expiration Date: " + 
                cookie.Expires.ToString() + "");
        }
        Label1.Text = sb.ToString();
    }


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpCookie Example</title>
</head>
<body>
    <form id="form1" runat="server">

</form> </body> </html>

 

So the above example clear how to use Cookie.

Limitation of cookies:

Since the number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client’s hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data.

4. Control State

Whenever we use view state to preserve some information but When the user is disabled view state explicitly than the control will not work as expected. So For expected results for the control, we have to use Control State property. Hence control state is separate from view state.

5. Query string

 

Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.A typical query string looks like this:

https://www.loginworks.com/default.aspx?category=basic&sale=100

It starts with a question mark (?) in URL and includes two attribute pairs, one called “category” and the other called “sale.”

 

Server-side State management

The server-side state management technique provides better security and reduces bandwidth. Generally, this option is for storing page information that tends to have security than the client-side option, but they can use more web server resources which may lead to scalability issues when the size of the information is large.

Server-side State management Techniques:

1. Session

The Session State information is available to all pages opened by a user during a single visit. Generally, the session is used to uniquely identify a user (or say browser). This method stores the session specific information (that is values and objects is session state)  that is visible only within the session. This session state is available as the HttpSessionState class. The Session State which identifies the requests from the same browser during a limited time and it provides the ability to persist variable values for the duration of that session. The server use session ID to maintains the state of user information.

Example:

Let us see how to get and set value in Session

Session["Count"] = Convert.ToInt32(Session["Count"]) + 1;//Set Value to The Session
Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion 

ASP.NET provides two events to manage a session that is written in a special file called Global.asax in the root directory of the project.

  1. Session_Start
  2. Session_End

2. Application

This State information is available to all pages, regardless of which user request a page. The application state variables are the global variables for an ASP.NET application. The ASP.NET provides application state via the HttpApplicationState class. You can also store your application-specific values in application state

Example:

Let us see how to get and set value in Application

Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object 

ASP.NET provides two events to manage an application that is written in a special file called Global.asax in the root directory of the project.

  1. Application_Start
  2. Application_Error
  3. Application_End

3. Profile Properties

Profile Properties is used to store user-specific data. Unlike session state, the profile data is not lost when a user’s session expires. It uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. So it easily manages user information without requiring, creating and maintaining your own database. It can be used in both multi-computer and multi-process configurations. This property provides a generic storage system that allows you to define and maintain any kind of data while making the data available in a type-safe manner.

Advantages of  State management:

Let us see Advantages to State Management:

Client-side advantages:

  • Scalable – each client connecting to server consumes resources. If the site has hundreds of simultaneous users the memory used can be a limiting factor. Client-side storage of state information limits the burden on the server.
  • Supports multiple web servers – allows incoming requests to be spread across multiple servers. Each client provides all info any web server needs to process the request. With server-side state management, if the client changes servers in the middle of the session then the new server may not have all information required. To get around this need intelligent load balancers or centralized state management.

Server-side advantages:

  • Security – Since any user changes client-side state information. Thus should not store sensitive info such as passwords, access levels, authentication status, etc.
  • Reduced bandwidth – sending state info back and forth to the client increases bandwidth requirements and so slows page load times and Should store large amounts of info (> 1kb) server side.

There is also persisted state – data stored in the database. Could decide to store all info in the database, but this may put too much pressure on the database. In this case may be better to store real, transactional data in the database and rely on other techniques for managing the transient state data. So for the security purpose server-side state management is useful rather than client-side state management.

Conclusion

In this blog, we saw how State management is an essential means to preserve the state of a control, web page, object/data, and user. So we have talked about various types of state management techniques in this blog. Since all web apps demand a high level of state management So I tried to put together an overview blog on the various state management techniques.
Thank you for Reading!!!

 

Get in Touch

Leave a Comment