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:
- Hidden Field
- Cookie
- View State
- 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:
- Session State
- Application State
So, it is time to go in details about every technique.
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.
-
- string myname = "Mukesh Kumar";
- HiddenField1.Value = myname.ToString();
- 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.
- Response.Cookies["UserName"].Value = "Mukesh Kumar";
- Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(2);
-
- HttpCookie myCookie = new HttpCookie("Session");
- myCookie.Value = DateTime.Now.ToString();
- myCookie.Expires = DateTime.Now.AddDays(1);
- 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.
- <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.
- protected void Page_Load(object sender, EventArgs e)
- {
- if (IsPostBack)
- {
- if (ViewState["UserName"] != null)
- {
- string userName = Convert.ToString(ViewState["UserName"]);
- }
- else
- {
- ViewState["UserName"] = "Guest";
- }
- }
- }
- protected void Submit(object sender, EventArgs e)
- {
- lblUserName.Text = ViewState["UserName"].ToString();
- }
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.
- protected void btnSend_Click(object sender, EventArgs e)
- {
- Response.Redirect("Default2.aspx?UserId=" + txtUserId.Text + "&UserName=" + txtUserName.Text);
- }
Get the query string values as in the following way:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- lblUserId.Text = Request.QueryString["UserId"];
- lblUserName.Text = Request.QueryString["UserName"];
- }
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- lblUserId.Text = Request.QueryString[0];
- lblUserName.Text = Request.QueryString[1];
- }
- }
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.
-
- void Session_Start(object sender, EventArgs e)
- {
-
- Session["UserName"] = "Guest";
- }
-
-
- Session["UserName"] = Convert.ToString(txtLoginUser.Text);
-
-
- 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.
-
- void Application_Start(object sender, EventArgs e)
- {
- Application["OnlineUser"] = 0;
- }
-
-
- Application.Lock();
- Application["OnlineUser"] = Convert.ToInt32(Application["OnlineUser"]) + 1;
- Application.UnLock();
-
- lblOnlineUser.Text = Application["number"].ToString();
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.