State Management

Preserving information on the page or state between the round trips to the server is called state management. We are going to learn about Cookies, Query string, View State, Session & Applications.

Client side state management, Server side state management
Basically there are two main types of state management; i.e Client side and Server side

In client side state management the information or data or state is stored on the client's machine . We cannot store sensitive data like user credentials at client side because it is not secured and we can only store limited data.

In server side state management, data or information or state is stored and maintained on server. We can store sensitive data at server side safely.

ViewState

By default, view states are used to store single page information and control values between server round trips. It preserves page values and web control property values.

When data is processed on the server, the current state of page & control values is held during postback & then they are put into the hidden field of the page.

Example 

  1. protected void button_click(object sender, EventArgs e) {  
  2.     int count = 0;  
  3.     for (int i = 0; i < 5; i++) {  
  4.         count += 1;  
  5.         ViewState["noOfCount"] = count;  
  6.     }  
  7.     if (!string.IsNullOrEmpty(ViewState["noOfCount"] as string)) {  
  8.         string str = "Total count is" + (int) ViewState["noOfCount"];  
  9.     }  
  10. }   

In the above example count value is stored into the ViewState and counter is incremented on every postback.

Drawback

  1. One of the most dangerous drawbacks is, due to ViewStatem performance issues arise. ViewState generates a  large amount of data i.e page data and all control property values so each time when server round trip occurs,  data is sent to server, and  it affects the performance of the website.To overcome or reduce this problem disable the ViewState whenever it's not needed.

Syntax for disabling view state for entire page

At page directory set False value to EnableViewState Attribute

  1. <%Page EnableViewState="False" %>   

Syntax for disabling ViewState for particular control

  1. <asp:textbox id="txtName" runat="server" EnableViewState="False"/>   

View state can be used in a single page.

It stores information in hidden field, it can be seen in source code in browser. Hence it is not secure.

Query String



Query string is used to pass information from one page to another, the data is actually appended to the URL (placed into the URL)

In client-side state management, the data is passed from one page to another by appending it into the URL. It is the most commonly used approach to implement search engine.

It is in the form of name and value pairs & is visible on web browser on address bar. The query string starts with a question mark (?) and includes attribute and their values. Multiple data is also passed through query string, and two attributes are separated using the & symbol.

eg.

www.institutecontrol.com/StudentList.aspx?Name=Abhishek&Id=4

On page1
  1. <asp:HyperLink ID="hlnkSearch" runat="server" NavigateUrl="www.institutecontrol.com/StudentList.aspx?Name=Abhishek&Id=4" Text="List"/>  
Pass value from page1 to StudentList.aspx with data Abhishek and 4 which are assigned to attribute Name and Id correspondingly. Separate the first attribute by using ? symbol and successive attributes are separated by the & symbol

On another page (list page)
  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     if (!string.IsNullOrEmpty(Request.QueryString["Name"] as string)) {  
  3.         string name = Request.QueryString["Name"].ToString();  
  4.     }  
  5.     if (!string.IsNullOrEmpty(Request.QueryString["Id"] as string)) {  
  6.         int id = (int) Request.QueryString["Id"];  
  7.     }  
  8. }  
Retrieve data passed from query string to another page by Request.QueryString[attribute_Name.

Drawback

Data is placed in URL so it's visible; that's why we cannot send sensitive data by query string.

Cookies


Cookie is a client side state management technique to store data in small text files stored in the client's RAM or hard disk. A cookie can be either temporary or permanent.

Example

Cookie is created and read using HttpCookie class.

Create Cookie
 
  1. HttpCookie studentInfo = new HttpCookie("StudentInfo");  
  2. studentInfo ["Name"] = "Abhishek";  
  3. studentInfo ["Course"] = ".net;  
  4. studentInfo.Expires=DateTime.Now.AddDays(1);  
  5.   
  6. Response.Cookies.Add(studentInfo );   
Reading cookie

  1. string student_Name = Request.Cookies["Name"].Value;string Course = Request.Cookies["Course"].Value;   

To set expiration for cookie object

  1. studentInfo.Expires=DateTime.Now.AddDays(1);   

It will clear the cookie within one day.

Session

Session carries user specific data or session data. It means, suppose one user logged into one website then data is stored into the session and that data is carried out in all pages of that website until the user logs out.

Session has a timeout period after timeout period or after user logout session data is lost

Create Session 

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     Session["UserName"] = "Abhishek";  
  3. }  

Reading Session

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     if (!string.IsNullOrEmpty(Session["UserName"] as string)) {  
  3.         string name = Session["UserName"].ToString();  
  4.     }  
  5. }  

Limitation Of Seeion

  • Session is server side state management and session state variable stays in memory until it's removed, so it affects the site performance.
  • If large data is stored into the session state variable then it also gives adverse impact on site performance

Application

Objects that can be globally accessed by any user of the same web application are stored in the application. It is an application specific state management.

Application state variable can be globally accessed so it is declared into the global.asax file.

Create Application

It will declare into the global.asax file in that Application_Start event

  1. void Application_Start(object sender, EventArgs e) {  
  2.     Application["count"] = 0;  

Read Application

  1. Application["count"]=(int)Application["count"]+1;   

Application state variable is mostly used to calculate and show the number of viewed user in real life.

Limitation

Global.asax files load at every event and get fired on every round trip, so if we place more data in global.asax file then loading time will increase and it negatively impacts performance.