State Management In ASP.NET

ASP.NET developers use various available technologies for State Management. We can classify them as client side state management or server side state management.

As we know Web pages are based on the HTTP Protocol which is a stateless protocol, which means that there is no information about the request, such as where they are coming from; i.e. whether the request is from the same client or from a new client. Since the page is created each time, the page is requested, then destroyed. So we can say that the state is not maintained between client requests by default.

ASP.NET developers use various available technologies for State Management. We can classify them as client side state management or server side state management.

State Management In ASP.NET
 

CLIENT SIDE STATE MANAGEMENT

 

View State

 
ViewState is an approach to saving data for the user. Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks. ViewState is the mechanism that allows state values to be preserved across page postbacks and by default, EnableViewState property will be set to true. In a nutshell, ViewState,
  • Stores values per control by key name, like a Hashtable.
  • Tracks changes to a View State value's initial state.
  • Serializes and Deserializes saved data into a hidden form field on the client.
  • Automatically restores View State data on postbacks.

    State Management In ASP.NET

Sample

  1. //To Save Information in View State   
  2. ViewState.Add ("NickName""Dolly");  
  3.   
  4. //Retrieving View state  
  5. String strNickName = ViewState ["NickName"];  

Here is a simple example of using the "ViewState" property to carry values between postbacks.

Code Example

  1. public int SomeInteger {  
  2.     get {  
  3.         object o = ViewState["SomeInteger"];  
  4.         if (o != nullreturn (int)o;   
  5.         return 0;  
  6.         //a default  
  7.     }  
  8.     set { ViewState["SomeInteger"] = value; }  

Control State


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

There are two methods you have to implement in your custom control.

  • Load Control State

  • Save Control State

    State Management In ASP.NET

Code Example

  1. public class ControlStateWebControl : Control  
  2. {  
  3.     #region Members  
  4.     private string _strStateToSave;  
  5.     #endregion  
  6.     #region Methods  
  7.     protected override void OnInit(EventArgs e)  
  8.     {  
  9.         Page.RegisterRequiresControlState(this);  
  10.         base.OnInit(e);  
  11.     }  
  12.     protected override object SaveControlState()  
  13.     {  
  14.         return _strStateToSave;  
  15.     }  
  16.     protected override void LoadControlState(object state)  
  17.     {  
  18.         if (state != null)  
  19.         {  
  20.             _strStateToSave = state.ToString();  
  21.         }  
  22.     }   
  23.     #endregion  
  24. }  

Hidden Fields


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. These fields are not rendered by the browser, rather it's just like a standard control for which you can set its properties. If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

State Management In ASP.NET
 
Sample
  1. //Declaring a hidden variable  
  2. protected HtmlInputHidden hidNickName;  
  3.   
  4. //Populating hidden variable  
  5. hidNickName.Value = "Page No 1";  
  6.   
  7. //Retrieving value stored in hidden field.  
  8. string str = hidNickName.Value;   

Code Example

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if(!IsPostBack)|  
  4.         Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);  
  5. }  
  6. protected void Button1_Click(object sender, EventArgs e)  
  7. {  
  8.     HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();   
  9.     Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);  

Cookies


A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. Every time a user visits a website, cookies are retrieved from the user machine and help identify the user.

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server.

State Management In ASP.NET

Sample
  1.  // Creating a cookie  
  2. myCookie.Values.Add("muffin""chocolate");  
  3. myCookie.Values.Add("babka""cinnamon");  
  4.   
  5. // Adding Cookie to Collection  
  6. Response.Cookies.Add(myCookie);  
  7.   
  8. // Getting Values stored in a cookie  
  9. Response.Write(myCookie["babka"].ToString());  
  10.   
  11. // Setting cookie path  
  12. myCookie.Path = "/forums";  
  13.   
  14. // Setting domain for a cookie  
  15. myCookie.Domain = "forums.geekpedia.com";  
  16.   
  17. // Deleting a cookie  
  18. myCookie.Expires = DateTime.Now.AddDays(-1);  

Code Example

  1. //Storing value in cookie  
  2. HttpCookie cookie = new HttpCookie("NickName");  
  3. cookie.Value = "David";  
  4. Request.Cookies.Add(cookie);  
  5. //Retrieving value in cookie  
  6. if (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)  
  7.          lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();  
  8. else  
  9.          lblNickName.Text = "Welcome Guest";   

Query String


A Query string is used to pass the values or information form one page to another page. They are passed along with URL in clear text. Query strings provide a simple but limited way of maintaining some state information. When surfing the internet you should have seen weird internet addresses such as:

http://www.localhost.com/Webform2.aspx?name=ABC&lastName=XYZ

This HTML address uses a QueryString property to pass values between pages.

State Management In ASP.NET

Syntax

Request.QueryString(variable)[(index)|.Count]

Code Example

  1. using System;  
  2. using System.Web.UI;  
  3.   
  4. public partial class _Default : Page  
  5. {  
  6.     protected void Page_Load(object sender, EventArgs e)  
  7.     {  
  8.         string v = Request.QueryString["param"];  
  9.         if (v != null)  
  10.         {  
  11.             Response.Write("param is ");  
  12.             Response.Write(v);  
  13.         }  
  14.         string x = Request.QueryString["id"];  
  15.         if (x != null)  
  16.         {  
  17.             Response.Write("   id detected");  
  18.         }  
  19.     }  
  20. }  

SERVER SIDE STATE MANAGEMENT


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.

In classic ASP, an application object is used to store connection strings. It's a great place to store data that changes infrequently.

State Management In ASP.NET

Code Example 1
  1. //Stroing information in application state  
  2. lock (this)  
  3. {   
  4.        Application["NickName"] = "Nipun";  
  5. }  
  6. //Retrieving value from application state  
  7. lock (this)  
  8. {  
  9.       string str = Application["NickName"].ToString();  
  10. }  

Code Example 2

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     // Code that runs on page load  
  3.     Application["LoginID"] = "Nipun";  
  4.     Application["DomainName"] = "www.nipun.com";  
  5. }  

Session State


ASP.NET 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.

State Management In ASP.NET

Sample
  1. //Storing informaton in session state  
  2. Session["NickName"] = "ABC";  
  3.   
  4. //Retrieving information from session state  
  5. string str = Session["NickName"];   

Code Example

  1. object sessionObject = Session["someObject"];  
  2. if (sessionObject != null)  
  3. {  
  4.  myLabel.Text = sessionObject.ToString();  
  5. }  

Profile Properties


ASP.NET provides a feature called profile properties, which allows 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.

State Management In ASP.NET

Sample

  1. <profile>  
  2.   <properties>  
  3.     <add item="item name" />  
  4.   </properties>  
  5. </profile>  

Code Example

  1. <authentication mode="Windows" />   
  2. <profile>    
  3.   <properties>    
  4.      <add name="FirstName"/>    
  5.      <add name="LastName"/>    
  6.      <add name="Age"/>    
  7.      <add name="City"/>    
  8.   </properties>    
  9. </profile>