State Management Technique Available in ASP.NET

In this article, you will learn about the state management technique available in ASP.NET.

As we know that HTTP is stateless protocol, it means after every request data gets lost. Browser does not know about previous data and we cannot get earlier request data. So, basically the state of the page or control lost after every page request.

State Management is a technique or process through which we can maintain the page information between multiple requests for same or multiple pages. So, using this we can get the earlier page or control data on the same page or on different page at the time of next request.

State Management techniques available in the following types:

Client Side State Management

It is used to store the state related information on the client side. So, every time to get data there is no need to hit the server. The main benefit is that you relieve the server from extra burden of storing the state related information. And you can save the server memory and utilize it in different task.
There is one drawback to use client side state management; you can store the sensitive data like your password, bank details, etc. on the client side.

The following techniques are used in client side state management:
  1. Hidden Field
  2. Cookie
  3. View State
  4. Query Strings

Server Side State Management

It works same as client side state management technique work but it stores the data on server rather than client side. Web server stores the data in web server memory. It is safe and secure for your sensitive data.

The following techniques are used in server side state management:

  1. Session State
  2. Application State

So, it is time to go in details about every technique.

State management

Client Side- Technique

Hidden Field

It is used to store the small data on the client side. It is invisible control that contains the small data like a single variable value in it. The data of hidden filed is never shown by the browser. If you want to see the value of hidden field, you can view by page source. There is not any encryption technique applied to encrypt the hidden field data. ViewState use hidden field to store the data internally.

  1. //Storing in Hidden Field  
  2. string myname = "Mukesh Kumar";  
  3. HiddenField1.Value = myname.ToString();  
  4. lblUserName.Text = HiddenField1.Value;  
Cookie

It is nothing but a small text file which stores the small pieces of data using client’s browser. The main use of the cookie is that it is only for identifying the user who is visiting the web application by their specific data that is stored into the cookie.

When cookie is persistent then it stores into the text file and when it is temporally based then it saves into the client browser. On the page request, server connects to cookie and gets the relevant information about visitors. You can take a simple example of cookie i.e login page.

We can easily create, read and delete the cookie using the code.
  1. Response.Cookies["UserName"].Value = "Mukesh Kumar";  
  2. Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(2);  
  3.   
  4. HttpCookie myCookie = new HttpCookie("Session");  
  5. myCookie.Value = DateTime.Now.ToString();  
  6. myCookie.Expires = DateTime.Now.AddDays(1);  
  7. Response.Cookies.Add(myCookie);  
ViewState

In ASP.NET MVC, ViewState is used to store the state of the control or object data or any data source, etc. It contains the stored data after page is posted. So, we can say, it is a technique to retain the value or data between multiple requests for same page. We cannot access the value of ViewState on other page.

When we use the ViewState to store the page information or any control information then ViewSate hash the data into a string and saves it into the hidden field. If your data is too long or heavy then ViewState creates multiple hidden fields and save the data in chunk.
  1. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value=" /wEPDwUKMTIxNDIyOTM0Mg9kFgICdAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA24IDEd6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGdnqjqHlH66cdw==" />  
ViewState is a dictionary object so our data is stored into the ViewState as key-value pair. EnableViewState property is used to enable or disable the ViewState. You can make it either True or False.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (IsPostBack)  
  4.     {  
  5.         if (ViewState["UserName"] != null)  
  6.         {  
  7.             string userName = Convert.ToString(ViewState["UserName"]);  
  8.         }  
  9.         else  
  10.         {  
  11.             ViewState["UserName"] = "Guest";  
  12.         }  
  13.     }  
  14. }  
  15. protected void Submit(object sender, EventArgs e)  
  16. {  
  17.     lblUserName.Text = ViewState["UserName"].ToString();  
  18. }  
Query String

Sometimes, it is required to send some specific information on the other page, so using the query string we can hold the value and send it to other page easily. It is mainly used to store the variables as parameters such as you can see that most of the websites use query string in search page. In that the terms entered by user is showed in the browser.

You can see above url, query string values appear into the url, so never pass some sensitive data into the query string. There is some limitation of query string, you cannot pass too much characters into the query string. There is some limit based on the browsers.

Pass the query string values as in the following way.
  1. protected void btnSend_Click(object sender, EventArgs e)  
  2. {  
  3.    Response.Redirect("Default2.aspx?UserId=" + txtUserId.Text + "&UserName=" + txtUserName.Text);  
  4. }  
Get the query string values as in the following way:
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         lblUserId.Text = Request.QueryString["UserId"];  
  6.         lblUserName.Text = Request.QueryString["UserName"];  
  7.     }  
  8. }  
  9. protected void Page_Load(object sender, EventArgs e)  
  10. {  
  11.     if (!IsPostBack)  
  12.     {  
  13.         lblUserId.Text = Request.QueryString[0];  
  14.         lblUserName.Text = Request.QueryString[1];  
  15.     }  
  16. }  
Server Side- Technique

Session State

In ASP.NET you can use the session object to store the value which is accessible throughout the application in single browser. Some time it is required to store the value which might be sensitive and it should be accessible on every page of the application, in that scenario you can go with session object for storing the data.

Mostly you have seen that Session is used to store the user related information which needs to be accessed on every page for processing. The Session cannot be accessible outside of the browser where it has been created. Every browser creates own session.

If you leave the application or your session is going to time out then you will not access the session data. It means, the session data lost after specific time period. So, again browser will create a new session for you. Actually, Session stores the data as key/value pair.
  1. //global.asax  
  2. void Session_Start(object sender, EventArgs e)  
  3. {  
  4.    // Code that runs when a new session is started  
  5.    Session["UserName"] = "Guest";  
  6. }  
  7.   
  8. //store the session value  
  9. Session["UserName"] = Convert.ToString(txtLoginUser.Text);  
  10.   
  11. //get the session value  
  12. lblUserName.Text = Session["UserName"].ToString();  
Application State

It is a global storage to store the value which will be accessible to all the pages. It also store the data into key/value pair. Server auto manages all the activity on application state data and does not expose it to client. The information stored into application state is accessible to all the page.

So, application state is best place for storing such type of data which is useful for entire users who is using the same application. I want to confirm here that the application state data is not permanent. If you restart or shutdown your application then application state will lost.
  1. //global.asax  
  2. void Application_Start(object sender, EventArgs e)  
  3. {  
  4.    Application["OnlineUser"] = 0;  
  5. }  
  6.   
  7. //In web pages  
  8. Application.Lock();  
  9. Application["OnlineUser"] = Convert.ToInt32(Application["OnlineUser"]) + 1;  
  10. Application.UnLock();  
  11.   
  12. lblOnlineUser.Text = Application["number"].ToString();  
Table

So, finally we can say client side as well as server side state management technique has their own importance and we can use all these as per requirement in our application.

Thanks for reading this article, hope you enjoyed it.