Jitesh Byahut 9/28/2014 2703

State Management in Asp.Net

Http protocol is stateless. So maintaining state between post backs by user is very difficult. Asp.Net framework provides state management technique to maintain state between post backs. Asp.Net provides two types of state management, client side and server side.

Two types of State Management in Asp.Net

Client Side

Client side state management technique stores information on client side like browser or client computer. Benefit of client side is to reduce the burden of server to store state information.

Query String

Hidden Field

Control State

Cookies

View State

Server Side

Server side state management technique stores information on server side.

Application State

Session State

Query String

Query string is client side state management variable. This is very easy to use. Basically we are using query string to send small amount of text from one page to another with help of page url. Just after page url you have to add ? sign and after that add your query string key and value. Whatever data you send through query string that visible to everyone.

Below codes is redirecting to Default4.aspx page and added a query string “Name” that value is Amit.

// Use Query String to send Name to next page

Response.Redirect("Default4.aspx?Name=asphelps");

On Default4.aspx, first check that query string is available or not. If available then retrieve that query string value using query string name.

// Retrieve Query String Value

if (Request.QueryString["Name"] != null)

{

    string name = Request.QueryString["Name"].ToString();

}

Encoded Query String

We learn that query string is very easy to use but apart from using it have some disadvantage that query string cannot accept Space and & characters. When you send space in query string you will see in url that space is replaced to %20 and whenever you send any query string that value contains & character then while retrieving it show only that text that comes before & sign. For example, if you are sending query string Name that value is Tom&Jerry then on other side it will retrieve as Tom only.

// Send Query String

    Response.Redirect("Default4.aspx?Name=" + Server.UrlEncode(txtName.Text) +

"&City=" + Server.UrlEncode(txtCity.Text));

Hidden Fields

Hidden field is very simple control to store small amount of data. It is a asp.net tool that present on web page. You can store data in hidden field from page side or C# page side. benefits of hidden field is that it never lost stored values during post backs.

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

Store data in hidden field

// Use Hidden Field to store Name

HiddenField1.Value = "asphelps";

Retrieve stored data from hidden field.

 

// Retrieve Hidden Field value

string name = HiddenField1.Value;

Cookies

Cookies are used to store small amount of data. Best example of cookies is to store login userid

You can create a new cookie by using Response.Cookies that contains collection of cookies which is sent from web server to web browser.

Creating Cookie

// Creating a Cookies

Response.Cookies["user"].Value = "Jitesh";

You can retrieve cookies values by their name, but remember that before retrieving cookies value, first check that cookies is exists or not otherwise it will throw an exception like : System.NullReferenceException: Object reference not set to an instance of an object.

Reading Cookie

// Reading Cookies Value

if (Request.Cookies["user"] != null)

{

     string name = Request.Cookies["user"].Value;

     Response.Write("Cookies Value - " + name);

}

Persiste Cookies

Cookies name is case sensitive. When you will close the browser then cookies lost their values. If you want to create cookies that containing values to the specified date no matter how many time browser is closed, on that time need to create persistent cookies that contains expiry date of cookies.

// Creating Persistent Cookies

Response.Cookies["user"].Value = "Jitesh";

Response.Cookies["user"].Expires = DateTime.Now.AddDays(10);

View State

View state is a client side state management mechanism. View state does not stored data on server side. Once you stored data in view state then you can retrieve that data from anywhere on the page.

Creating View State

Storing data in view state is very easy. You can store data in view state by assigning a key that will use to retrieve view state stored data. Below codes are showing to storing data in view state.

// Use ViewState to store Name

ViewState["Name"] = "asphelps";

 

Reading View State

Below codes are showing that retrieving data from view state. While retrieving you have to cast data type.

// Retrieve ViewState value

if (ViewState["Name"] != null)

{

    string name = ViewState["Name"].ToString();

}

View State Encryption

When you stored data into view state then internally its store into a html hidden field. View state stores data in hidden field as hashed base64 encoded string format. Hidden field hashed string can easily decoded. So its security risk that someone can change or modify that data if data is highly sensitive. To overcome these problems use view state EnableViewStateMac or viewStateEncryptionMode property.

1. Using EnableViewStateMac

2. Use viewStateEncryptionMode

Disadvantage of View State

1. Performance issues

2. Security concern

Control State

View state use to preserve page and page control values between round trips of the page. But, if view state disable for the page, then view state of the page controls is not maintained. So overcome this problem use control state that cannot be disabled. Control state can store control state. By default, the Asp.Net framework stores control state in the page hidden field same as view state.

On post back, Asp.Net deserializes the content of hidden field and loads state into each control that is registered for control state.

You can implement control state by overriding following methods of the base class:

1. OnInit - that contains two methods:

     a. Page.RegisterRequiresControlState(this)

     b. base.OnInit(e)

2. SaveControlState

3. LoadControlState

Session State

Session State is one of the important state management variable in Asp.Net. It’s working on server side. Advantage of session state is that once you store your data in session and access that data from anywhere in the application across multiple pages. Advantage of session state over cookies is that session can store any type of data as well as complete dataset whereas cookies can store only small amount of data.

Create Session

A new session can be created by specifying session name in session variable. For example, in below code we are creating a new session that name is UserName. In this session, we are storing simply a string value Asphelps. You can store any type of object data in session state.

Session["UserName"] = "Asphelps";

Read Session

Once you created session then, you can retrieve stored object in session from anywhere in the application. Use below code to retrieve your session data from any page in the application.

if (Session["UserName"] != null)

{

     string userName = Session["UserName"].ToString();

}

End Session

You can stop user session any time in the application. You have three option to stop user session.

1. Abandon - End user session in the application.

2. Remove - Remove a particular session in the application.

3. Clear - Clear all session object.

// Remove UserName session

Session.Remove("UserName");

// End a user session

Session.Abandon();

// Clear all session items

Session.Clear();

Control Session Timeout

When you are using session then session will expire after specific time. This time is known as session timeout. Default session timeout value is 20 minutes. But you can increase session timeout using session's TimeOut propery by declaring on page or in Web.Config.

<system.web>

    <sessionState timeout="60" />

</system.web>

Application State

Application state is server side state management variable. Application state stored data in memory on the server. Application state is global storage mechanism that access by all the page by all user and sessions. It is very useful to store small amounts of data that is common for all users. Application state lost their stored values when exception occurred or application restarted.

// Create Application State

Application["AppName"] = "Asphelps";

Retrieve stored value from application state.

// Retrieving value from Application State

string name = Application["AppName"].ToString();


Please give your feedback for improving this page