ASP.NET State Management

Definition-:

State Management: By name it means managing or preserving state of a control, web page or data.

Whenever we work on a page in asp.net have we ever thought how controls are able to get there state back after a post back. In real all the controls are stateless means when ever there is a postback state is lost. Then how are they able to get there state back after a postback???
This is all because of state management technique that asp.net provides for all the controls, web pages or data.

Now the question comes. How?
How are state management techniques used? Is it used on server side or client side? How many types of state management techniques are there?

Firstly, lets see what are the techniques of “State Management”-:

  1. View State
  2. Control State
  3. Hidden fields
  4. Cookies
  5. Query Strings
  6. Application State
  7. Session State
  8. Profile Properties

Now question comes are they server side or client side?
Let me answer, good news they are both.
They can be classified into-:

  1. Client Side, as well as
  2. Server Side

Client Side controls are-:

  1. View State
  2. Control State
  3. Hidden fields
  4. Cookies
  5. Query Strings

Server Side controls are-:

  1. Application State
  2. Session State
  3. Profile Properties

Now the confusion comes, how do we know where to use which technique.
Don’t worry we are discussing it next.
Firstly, lets discuss where to use client side controls.

Client-Based State Management

VIEW STATE-:

Viewstate is a page level state management process i.e. as long as user works on current page, state will be stored and as soon as user redirects to some other page, state will be lost.
View state stores user data temporarily after a post back i.e. in other words, we can say whenever user needs to store data temporarily after a postback, then view state is the preferred way.

For example-:

public class ViewSateExample : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 if(ViewState[“Value”] != null)
 lblTextBox.Text = ViewState[“Value”].ToString();
 else
 lblTextBox.Text = “ViewState missing...”;
 }

protected void Button_Click(object sender, EventArgs e)
 {
 ViewState[“ViewState”] = txtTextBox.Text;
 lblTextBox.Text = txtTextBox.Text;
 }
}

CONTROL STATE-:
In previous section we discussed about view state, but suppose view state is disabled explicitly by the user. In this case the control will not work as expected. So, to get expected result of the control we have to use control property.

Control state is simple to implement. Firstly, we need to override OnInit() method of the control and than add a call to Page.RegisterRequiresControlState() method with the control instance to be registered and lastly override LoadControlState and SaveControlState to save required information.

For eg:

public class: ExampleControl {
 private int iCurrentIndex = 0;

 protected override void OnInit(EventArgs e) {
 Page.RegisterRequiresControlState(this);
 base.OnInit(e);
 }

protected override object SaveControlState() {
 return iCurrentIndex !=0 ? (object)iCurrentIndex : null;
 }

protected override void LoadControlState(object state) {
 if(state != null) {
 iCurrentIndex = (int)state;
 }
 }
}

HIDDEN FIELD-:

Now the question arises what if the value of variable changes frequently. Both the method that we have discussed may be used but the fast and preferred method is hidden field. Hidden fields are used to store small amount of data on the client. It can store only one value for a variable at a time. It stores value in its Value property.

Hidden Field stores value in following way-:

<asp:HiddenField ID = “HiddenField” runat = “server” value = “Value” />

COOKIES-:

Cookie is a small file in the form of text file that is created by the browser for the ease of the user.
Cookie works as follows-:
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’s hard disk either permanently or temporarily. 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.

There are 2 types of cookies
1. Persistence – Cookies with an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
There are 2 ways to set it-:
First,

Response.Cookies[“PersistenceCookie”].Value = “This is Persistence cookie”;
Response.Cookies[“PersistenceCookie”].Expires = DateTime.Now.AddSeconds(10);

Second,

HttpCookie aPersistence = new HttpCookie(“Persistance”);
aPersistence.Value = “This is Persistence cookie”;
aPersistence.Expires = DateTime.Now.AddSeconds(10);
Response.Cookie.Add(aPersistence);

2. Non-Persistence – Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as log as browser is on. When user closes the browser the cookie will be discarded.
There are 2 ways to set it-:
First,

Response.Cookies[“NonPersistenceCookie”].Value = “This is non Persistence cookie”;

Second,

HttpCookie aNonPersistence = new HttpCookie(“nonPersistance”);
aNonPersistence.Value = “This is non Persistence cookie”;
Response.Cookie.Add(aNonPersistence);

How to read a cookie-:

if(Request.Cookies[“aNonPersistence”] !=null)
lbl.Text = Request.Cookies[“aNonPersistence”].Value;

QUERY STRINGS-:

A query string is information that is appended to the end of a page URL. It is carried with URL whenever page redirects.
For eg: http://www.example.com/QueryString.aspx?serial=1&rollno=17

The query string starts with a question mark (?) and includes two attribute, one called “serial” and the other called “rollno” with values 1 and 17 respectively.

Server-Based State Management

APPLICATION STATE-:

In previous section we discussed about client based state management, now lets discuss about server-based state management. ASP.NET allows us to save values of controls using application state. Application state is stored in the key/value dictionary. This stored data will be available to all users of the website.

ASP.NET provides three events that enable you to initialize Application variables :

  1. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.
  2. Application_End: Raised when an application shuts down. Use this to free application resources.
  3. Application_Error: Raised when an unhandled error or exception occurs. Use this to perform error logs.

Eg: Application[“Message”] = “Welcome to the Application.”;

SESSION STATE-:

Like Application state, this information is also in a global storage that is accessible for all pages in the Web application. Session state is stored in the Key/value dictionary. Session values can be used all over the application for the current user only who is logged in.
Eg: Session[“FirstName”] = FirstNameTextBox.Text;
Session[“LastName”] = LastNameTextBox.Text;

PROFILE PROPERTIES-:

Like session state this information is also user specific. But here the data remains even after session expires. Here we use ASP.Net profile to achieve this. ASP.Net profile associates information to the individual user and stores the data in a persistent format. We have flexibility to store scalar values, complex types, user defined properties.
All you need to do is :

  • Set profile provider
  • Set SQLProfileProvider
  • Define profile properties in web.config
  • Save your profile properties

 

Written By : Himanshu Dora, ASP.NET Developer, Mindfire Solutions

Advertisements

Posted on December 5, 2013, in ASP.Net and tagged , , , , , , . Bookmark the permalink. 1 Comment.

  1. awesome stuff ..!! very useful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: