Skip to content

State Management in ASP.NET Core MVC

State management means explicitly preserving the state of a control, web page, data, object or user in an application. It is needed because all ASP.NET web applications are stateless: by default, the state of the controls is lost each time a page is posted to the server.

For example, when a form is submitted, all form values are cleared. Suppose you submit a form with a lot of information and the server comes back with an error. You go back to the form to correct the information, and what happens? All the form values have been cleared, and you have to start all over again. The website did not maintain the state of its controls, so we need to store the page values at the time of the postback. We can do this with state management. Today, web applications need state management at every level, from individual controls to the whole application.

There are two types of state management techniques:

Client-side state management: in this technique, the state of the controls is kept on the client. Some client-side state management techniques are:

  • Hidden fields
  • View State
  • Cookies
  • Control State
  • Query strings

Server-side state management: in this technique, the state of the controls or users is kept on the server. Some server-side state management techniques are:

  • Session State
  • Application State

View State Management

View State is one of the most useful client-side state management techniques. It stores the page values at the time of the postback (when information is sent to and received from the server). ASP.NET pages provide the ViewState property as a built-in structure that automatically stores values between multiple requests for the same page.

When a form is submitted, all form values are cleared. Suppose you submit a form with a lot of information and the server comes back with an error. You go back to the form to correct the information, and all the form values have been cleared, so you have to start all over again. The website did not maintain the state of its controls, so we need to store the page values at the time of the postback. We can do this with the View State property of the controls.
Client-side state management does not use any server resources; it stores information on the client.

Advantages of View State: the main advantages of View State are:

  • It is easy to implement.
  • No server resources are required.
  • It has security features: the data can be encoded and compressed.

Disadvantages of View State: the main disadvantages of View State are:

  • There can be some performance overhead if we store a large amount of data.
  • View State values are stored in a hidden field in encoded form, but they can still be read easily.
  • It does not have good support on mobile devices.

When should we use View State?
We should use View State:

  • When the amount of data is small. The data is bound to the page controls, so large amounts of data cause performance overhead.
  • When the data is not sensitive.

When should we avoid View State?
We should avoid View State when:

  • The controls never change.
  • The controls are repopulated on every postback.
  • The control is an input control that changes only through user actions.

Where is View State stored?
View State stores the values of the page controls as a string that is hashed and encoded. It only contains information about the page and its controls, and it does not interact with the server. It stays with the page in the client's browser. View State uses a hidden field to store its information in an encoded format.
You can see the View State values by right-clicking the page and choosing View Source. You will see the following code:

input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
  value="2NvUlofSaheYe5BlK1m4Yh65gVDCn2o9F722HH3XvSMqUJWOzcs6F17MOkQ22rlkXxXff/2Ig="

Now look at the value: it looks like an encrypted string, but it is a Base64-encoded string, so it can easily be decoded.
Base64 makes a string suitable for HTTP transfer, and it also makes it a little harder to read.

View["xyz"]= 0; Stored 0 in xyz  //means it stores a variable.
View["xyz"]="hello this is Sudhir";  // means it stores the string value.
View[_classObject]=_objectofaClass;  //means it stores the object of a Class 

How can you store an object in View State? We can store an object in View State just like a string or an integer, but we need to convert it into a stream of bytes, because View State stores information in a hidden field in the page. So we need to use serialization. If the object we are trying to store in View State is not serializable, we get an error message.

[Serializable]
Public Class ClassName
{
    //Class members goes here
}

How to trace View State information: to trace your View State information, enable the Trace option in the page directive.

Page Title="" Language="C#" MasterPageFile="~/Sitemaster.Master" Trace="true"
TraceMode="SortByTime" AutoEventWireup="true"
CodeBehind="frmTokenGeneration.aspx.cs" Inherits="DigitalToken.Staff.frmTokenGeneration"

Now run your web application. You can see the View State size of each control, along with the control ID, in the control tree section.

Enable and disable View State: we can enable and disable View State for a single control as well as at page level. To turn off View State for a single control, set the control's EnableViewState property to false.

TextBox1.EnableViewState=false;

To turn off View State for the entire page, set EnableViewState to false in the page directive, as shown below:
Page language="C#" EnableViewState=false;

Session State Management in ASP.NET

A session is one of the most useful server-side state management techniques, used to store information for web pages. Each browser instance gets its own session. A single user can have multiple sessions by visiting your application from multiple browser instances on their machine, each with a different session ID.
Session is global data for a single user.

Session lets us store information in server memory. It can store any type of object, including our own custom objects.
Session data is stored separately for every client, which means session data is stored on a per-client basis.
As we know, HTTP is a stateless protocol: it cannot keep client information between pages. If a user enters some information and moves to the next page, that data is lost and the user cannot get it back. Session gives us a way to store that information.
State management using session is one of the best ASP.NET features, because it is secure, transparent to users, and we can store any kind of object in it.

Advantages of Session: the main advantages of Session are:

  • Session helps to maintain user state and data across the application.
  • Session is easy to implement, and we can store any kind of object in it.
  • Session stores data separately for each user.
  • Session is secure and transparent to users.

Disadvantages of Session: the main disadvantages of Session are:

  • Performance overhead with a large volume of data or users, because session data is stored in server memory and clients read the data from the server.
  • Overhead from serializing and deserializing session data, because in State Server and SQL Server modes the objects must be serialized before they are stored.

Session events: there are two session events available in ASP.NET.

  • Session_Start
  • Session_End
We can handle both these events in the Global.asax file of our web application. When a new session starts, the Session_Start event is raised; when the session is abandoned or expires, the Session_End event is raised.
Removing sessions: the following methods remove session data:
  • Session.Remove("name"): removes one item from the session state collection.
  • Session.RemoveAll(): removes all items from the session collection.
  • Session.Clear(): removes all items from the session collection. There is no difference between the Clear and RemoveAll methods.
  • Session.Abandon(): cancels the current session.