State management in Asp.Net

State management in Asp.Net

State management

State management covers how to preserve the state of users, web pages, objects, or controls across page submissions
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.

Types of State Management in ASP.NET
ASP.NET supports 2 types of state management approaches:
1. Client-side State Management
2. Server-side State Management

Client-side State Management

1. HiddenField Controls in ASP.NET

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();

2. ViewState in ASP.NET
ViewState is used for storing user data in an ASP.NET application.
if the user wants to store some data temporarily right after the postback, then ViewState should be an ideal choice.
View state is all about the state of the page and its controls (i.e page-level state management).  It is automatically maintained across the posts by framework. When page is sent back to the client for output, the changes in the properties of the page and its control are determined and stored in the value of hidden input field named _VIEWSTATE.
When page is again post back to the _VIEWSTATE field is sent to the server with HTTP request. View state is implemented using view state object defined by the StateBag class which defines collection of view state items. The StateBag class is data structure containing attribute or value pairs, stored as string associated with objects. User can set the view state as enabled or disabled for entire application or page.
A. For entire application user set the EnableViewState property in the <pages> section of web.config file.
B. For particular page user set the EnableViewState attribute of the page directive as <%@Page Language = “C#” EnableViewState = “false”%>.
C. For a control by setting the Control.EnableViewState property.

The StateBag class has the following properties:
Item(name),Count,Keys, Values

The StateBag class has the following methods:
Add(name, value), Clear, Equals(Object), Finalize, GetEnumerator, GetType, IsItemDirty, Remove(name), SetDirty, SetItemDirty, ToString

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();

3. Cookies in ASP.NET and C#
A cookie is a small text file generated and kept on the client’s machine, used to identify users uniquely. It is located on the client’s computer; it is not stored in the server’s memory.
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:
A. Persistence Cookies
Cookies that have a specific expiry date and time are called Persistence cookies. They maintain the data on the user’s machine.
They expire based on a date assigned by the webserver. Typically, these are seen as permanent cookies that do not expire.

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

//Read Cookie
if (Request.Cookies["defaultCookie"] != null)
  MyLabel.Text = Request.Cookies["defaultCookie"].Value;

B. Non-Persistence Cookies
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.

4. 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.
The ControlState is distinct from ViewState. Despite the fact that ViewState is enabled by default in ASP.NET applications, ControlState is sometimes used by developers who wish to employ custom controls to control the state of the application.

protected override void OnInit(EventArgs e)

protected override object SaveControlState()
    var state = new List<string>(); // save the 2 properties

    return state;

protected override void LoadControlState(object savedState)
    var state = (List<string>)savedState;
    Text = state[0];
    Text1 = state[1];

5. 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.
Query string is used to transfer data from one page to another page. Querystrings are simply the data that is appended to the end of web page URL.

Server-side State Management

1. 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.
HttpSessionState class is used to create the object of session state which defines collection of session state items.
SessionID, Item, count and TimeOut are the properties of HttpSessionState.
Add, Clear, Remove, RemoveAll, RemoveAt are methods of HttpSessionState.

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

2. 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.
HttpApplicationState class stores this object in the server memory. This object is represented by class file called as global.asax. Application state is mostly used to store the web site hit counters and other statistical data, global application data like tax rate, discount rate and to keep track of users visiting the site.
HttpApplicationState class has 2 properties such as Item and count.
HttpApplicationState class support few methods as Add, Clear, Lock, Unlock, Remove, RemoveAt, RemoveAll.

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

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.