State Management in ASP.NET

State Management in C#

In this ASP.NET programming tutorial, we will discuss the concept of state management and how it applies to the states of users and objects in web applications.

What is State Management?

State management in any application plays a vital role in preserving the states of users, web pages, objects, or controls. As .NET developers know, HTTP is a stateless protocol, so all online ASP.NET web applications are also stateless by default. That means the web application can not preserve the state of control for each page submitted to the server. In the modern era of web applications, there is a high demand for state management. But what, exactly, is state management, and how can it preserve the state of a web page or objects across page submissions? We will discuss these topics in the sections below.

Types of State Management in ASP.NET

ASP.NET supports two types of state management approaches:

  • Client-side State Management
  • Server-side State Management

Client-side State Management

In this section, we are going to discuss some of the controls used to maintain states on the client-side.

HiddenField Controls in ASP.NET

A HiddenField is a control in ASP.NET that is used to hold values in the client browser. It can store only one value for a variable and is used in situations where the value of a variable keeps updating – or gets updated – regularly. It cannot be seen, as it is not rendered on the browser. On every request made to the server, the HiddenField value is sent like any regular control value.

Here is an example of a HiddenField control in ASP.NET:

ASP.NET
--------------------------------------------------------------------

Here is an example of a HiddenField control in C#:

C#
--------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
   if (MyHiddenField.Value != null)
   {
    int newVal= Convert.ToInt32(MyHiddenField.Value) + 1;
    MyHiddenField.Value = newVal.ToString();
    MyLabel.Text = newVal.ToString();
   }
} 
 

Read: Exception Handling in C#

ViewState in ASP.NET

ViewState is used for storing user data in an ASP.NET application. It stores data in the HiddenField of generated HTML rather than on the server-side. For example, if the user wants to store some data temporarily right after the postback, then ViewState should be an ideal choice.

ViewState is primarily used for page-level state management. For example, the state of the control remains until the user is on the current page – once he navigates to another page, the state of the current page gets lost.

Here is an example of how to use ViewState in C#

C#
--------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["counter"] != null)
        {
            int value = Convert.ToInt32(ViewState["counter"]) + 1;
            MyLabel.Text = value.ToString();
            ViewState["counter"]= value.ToString();
        }
    }
}
 
protected void Button_Click(object sender, EventArgs e)
{
       MyLabel.Text= ViewState["counter"].ToString();
}

Cookies in ASP.NET and C#

A cookie is a small text file used to identify users uniquely. It is located on the client’s computer; it is not stored in the server’s memory.

You can say a cookie is a small file generated and kept on the client’s machine that holds information about the user. When a user requests a new page, the server generates a cookie and delivers it to the client, along with the requested page. The client then receives and keeps that cookie either permanently, or temporarily, in the browser.

Whenever the user requests the same site, the browser checks for the existence of a cookie associated with that site. If the cookie for that site is present, that cookie is sent to the server along with the request; otherwise, that request would be considered a new request.

There are two types of Cookies:

  • Persistence Cookies
  • Non-Persistence Cookies

Read: Project Management Software for .NET Developers

Persistence Cookies in C#

Cookies that have a specific expiry date and time are called Persistence cookies. They maintain the data on the user’s machine (user’s hard disk folder), such as sign-on information or settings. They expire based on a date assigned by the webserver. Typically, these are seen as permanent cookies that do not expire.

Here is an example showing how to create persistence cookies in C#:

C#
--------------------------------------------------------------------
Response.Cookies["defaultCookie"].Value = "This is an example of Persistence Cookie";
Response.Cookies["defaultCookie"].Expires = DateTime.MaxValue; 
 

Here is another example that shows how to read a cookie using C#:

C#
--------------------------------------------------------------------
if (Request.Cookies["defaultCookie"] != null)
{
  MyLabel.Text = Request.Cookies["defaultCookie"].Value;
}

Non-Persistence Cookie

Non-Persistence cookies are not stored permanently on the user’s machine. They maintain information as long as the user accesses the same browser. Once the browser is closed, the cookie gets discarded.

To create a non-persistence cookie, simply do not add an expiration date.

Control State in C#

Control state is another client-side state management mechanism. Users have the option to intentionally disable the ViewState feature and in such case, if the ViewState is holding some control information, then the control’s value could be lost. Because of this, we must use the ControlState attribute to get the expected value of the control.

Note that ControlState is different than ViewState. Although ViewState is enabled by default in an ASP.NET application, sometimes a developer may want to use custom controls to manage the state of the application and therefore we use ControlState.

QueryString in C#

You can use QueryString to store values in the URL. The value of the query string can be seen in the URL and is visible to all users.

Read: Regular Expressions in C#

Server-side State Management

Below we briefly cover state management as it related to serv-side management.

Session Management in C#

Session management is a powerful technique used for preserving data over sessions. Session is used to store user information and to uniquely identify a user (or a browser). ASP.NET uses a Session ID, which is generated by the server, to keep track of the status of the current user’s information. When a new user submits a request to the server, ASP.NET automatically generates a Session ID and that Session ID is transmitted with every request and response made by that particular user.

Following is a typical example showing how to get and set values in Session using C#:

C#
--------------------------------------------------------------------
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;  //Set Value to The Session
MyLabel.Text = Session["Counter"].ToString(); //Get Value from the Session 

Application State Management in C#

Application state management is another technique for maintaining the state on the server-side. The data persisting in the application state is shared by all users and that data can be accessed from anywhere within the application. You can think of this approach as Application-level state management. But note that the amount of data to be stored in the application state should be minimal.

Here is some example code showing how to set and get the value of an application state in C#:

C#
--------------------------------------------------------------------
Application["Counter"] = Convert.ToInt32(Application["Counter"]) + 1; // Set the value of Application object
 
MyLabel.Text = Application["Counter"].ToString();  //Get the value of Application object

Conclusion to State Management in C#

In this article, we have seen how important it is to preserve the state of the user, object, or web page in a web application. Since all modern web applications have a high demand for state management, programmers must know about various strategies of state management. We have only just begun to scratch the surface of what is possible with state management. Be sure to check back often for further C# state management tutorials.

Read more C# programming tutorials.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Must Read