blog

Home / DeveloperSection / Blogs / State Management in Asp.Net

State Management in Asp.Net

Sumit Kesarwani4149 29-Dec-2013

In this blog, I’m explaining the state management in asp.net.

Web pages are based on HTTP which is a stateless protocol means there is no information about the request that is whether the request is coming from the same client or from a new client. Web pages are created on each request and then destroyed, so the state is not maintained between client requests by default.

State management is the process by which ASP.NET let the developers maintain state and page information over multiple requests for the same or different pages. State management means to preserve state of a control, web page, object/data, and user in the application explicitly because all ASP.NET web applications are stateless, i.e., by default, for each page posted to the server, the state of controls is lost. Nowadays all web apps demand a high level of state management from control to application level.

Types of State Management

·         Client side state management

·         Server side state management

Client Side State Management

When we use client side state management, the state related information will be stored on client side. This information will travel back and forth with every request and response.

Pros

It takes more bandwidth as amount of data is traveling back and forth.

Cons

The information travel back and forth and hence this information can be intercepted by anyone in between.

Server Side State Management

Server side state management keeps all the information in user memory. It stores the sensitive information like passwords, credit card number and payable amount on server side.

Pros

It uses more memory usage on server.

Cons

User’s confidential and sensitive information is secure.

Client Side State Management Technique

·         Hidden Field
·         View State
·         Control State
·         Cookies
·         Query String

Server Side State Management Technique

·         Application State
·         Session State
·         Profile Properties

Hidden Field

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. A Hidden control is the control which does not render anything on the web page at client browser but can be used to store some information on the web page which can be used on the page. Hidden fields are used to store data at the page level. If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

Sample

publicHtmlInputHidden hiddenfield; //Declaring hidden variable
hiddenfield.Value = lblName.Text; //Setting value
string str = hiddenfield.Value; //Retrieving value

View State

View State is an approach to saving data for the user. View State provides page level state management i.e., as long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost. View State can store any type of data because it is object type. View state is enabled by default for all server side controls of ASP.NET with a property EnableviewState set to true.

Sample

ViewState.Add("Name", "Mark David");//Setting value
string name = ViewState["Name"].ToString();//Retrieving value

Control State

The purpose of the control state repository is to cache data necessary for a control to properly function. Control State is essentially a private View State for your control only, and it is not affected when View State is turned off. Control State is used to store small amounts of critical information. Heavy usage of Control State can impact the performance of application because it involves serialization and deserialization for its functioning.

Control state implementation is simple. First override the OnInit() method of the control and add a call for the Page.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information.

Sample

private string _strStateToSave;
protected override void OnInit(EventArgs e)
    {
        Page.RegisterRequiresControlState(this);
        base.OnInit(e);
    }
protected override object SaveControlState()
    {
        return _strStateToSave;
    }
 protected override void LoadControlState(object state)
    {
        if (state != null)
        {
            _strStateToSave = state.ToString();
        }
    }

Cookies

A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, 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, else that request is treated as a new request.

Sample

HttpCookie myCookie = newHttpCookie("Name");//Declare cookie
myCookie.Values.Add("Password", txtpassword.Text);//Setting value
string pwd = myCookie["Password"].ToString();//Retrieving value

Query String

A Query string is used to pass the values or information form one page to another page. Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. They can be used to store/pass information from one page to another to even the same page.

Sample
string str = Request.QueryString["Parameter"].ToString();//Retrieving value
Response.Redirect("default.aspx?name=ABC&lastName=XYZ");//Sending values

Application State

Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing a small amount of often-used data. If application state is used for such data instead of frequent trips to the database, then it increases the response time/performance of the web application

Sample

Application["Name"] = "Steve";//Setting value
string str = Application["Name"].ToString();//Retrieving value

Session State

Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. It is defined as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a session stored on a server.

Sample

Session["Name"] = "ABC";//Setting value
string str = Session["Name"]; //Retrieving value

Profile Properties

Profile properties allow you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. In this each user has its own profile object.

Sample

<profile>
  <properties>
    <add item="item name" />
  </properties>
</profile>


Updated 18-Sep-2014

Leave Comment

Comments

Liked By