State Management System in ASP.NET

Maintaining state is an important part of any web application. State Management System is a mechanism to track the user state, or data, which is significant with particular application. State management manages the state of an object on different request.

The HTTP protocol is the fundamental protocol of the World Wide Web. HTTP is a stateless protocol means every request is from new user with respect to web server. HTTP protocol does not provide any method of determining whether any two requests are made by the same person.

There are two types of state management system in ASP.NET.

  • Client-side state management
  • Server-side state management
Client-side state management stores information on the client’s computer and server-side state management stores the information in the server’s memory or a database.

Client side state management system

ASP.NET provides several techniques for storing state information on the client. These include the following:

  • View state: ASP.NET uses view state to track values in controls between page requests. It works within the page only. You cannot use view state value in next page. ASP.NET page contains a hidden form field named __VIEWSTATE. This hidden form field stores the value of the control’s property. When the page is posted back to the server, then the value of __VIEWSTATE is pulled out and re-creates the values of all the properties stored in View State.

  • Control state: The data that is associated with the server controls is called as control state. You can persist information about a control that is not part of the view state. If view state is disabled for a control or the page, the control state will still work.

  • Hidden fields: It store data without displaying that control and data to the user’s browser. This data is presented back to the server and is available when the form is processed. Hidden fields data is available within the page only (page-scoped data). It is rendered as an <input type= "hidden"/> HTML tag. Hidden field should not be used to store confidential data.

  • Cookies: Cookies are small piece of information that server creates on the browser. Cookies store a value in the user’s browser that the browser sends with every page request to the web server. It works on key/value pair.

  • There are two types of cookies:
    • Session cookies
    • Persistent cookies
  • Query strings: In query strings values are stored at the end of the URL. These values are visible to the user through his or her browser’s address bar. Query strings are not secure. You should not send secret information through the query string.

View state

View state is an inbuilt feature of ASP.NET that retains values between multiple requests for the same page. ASP.NET page contains a hidden form field named __VIEWSTATE. This hidden form field stores the value of the control’s property. By default view state is enabled for page and its controls. You can disable view state by setting the property EnableViewState as false. Storing too much data into View State can hamper the performance of web page.   
                                                              
Therefore we should take care while enabling and disabling the property EnableViewState.

Example

//writing information to view state
ViewState.Add("MyInfo", "Welcome");
//read information from view state
if (ViewState["MyInfo"] != null)
{
      string data = (string)ViewState["MyInfo"];
}


Hidden fields

Hidden fields in HTML are simply input fields and not visible on the browser during execution. Hidden fields are used to store data at the page level. Hidden fields are simple to implement for a page specific data and stores small amount of data. We should not use hidden fields for sensitive data. It has no built-in compression, encryption technique.

<asp:HiddenField ID="HiddenField1" runat="server" />

Example

//writing information to Hidden field
HiddenField1.Value = "Welcome";
//read information from Hidden field
string str = HiddenField1.Value;


Cookies

A cookie is a small amount of data that server creates on the client. Cookie is small text information. You can store only string values when using a cookie. When a request sent to web server, server creates a cookie, and sent to browser with an additional HTTP header.

The HTTP header looks like this:

Set-Cookie: message=Hello.

Here cookie name is message and value is hello.

If the cookies has created on a browser and user requests a page from the same application, then the browser sends a header that looks like this:

Cookie: message=Hello

There are two types of cookies:
  • Session cookies
  • Persistent cookies
A session cookie exists only till the user closes the web browser, the session cookie deleted permanently.

A persistent cookie, on the other hand, can available for months or even years. When you create a persistent cookie, the cookie is stored permanently by the user’s browser on the user’s computer.

Use of Cookies

Some common uses of cookies are:
  • Authentication of user.
  • Identification of a user session.
  • User's preferences.
  • Shopping cart contents.
  • Remember users between visits.

Creating and reading cookies

We can create cookies in different ways.

Example 1

Response.Cookies["Message"].Value = TextBox1.Text;
string msg = Request.Cookies["Message"].Value;


Example 2

HttpCookie UserCookies = new HttpCookie("Message");
UserCookies.Value = TextBox1.Text;
Response.Cookies.Add(UserCookies);
// Reading the cookie.
string roll = Request.Cookies["Message"].Value;


Example 3

//Writing Multiple values in single cookie
Response.Cookies["EmpCookies"]["EmpID"] = txtID.Text;
Response.Cookies["EmpCookies"]["FirstName"] = txtFirstName.Text;    
Response.Cookies["EmpCookies"]["LastName"] = txtLastName.Text;
Response.Cookies["EmpCookies"]["Address"] = txtAddress.Text;

//Reading Cookie.
string info;
   if (Request.Cookies["EmpCookies"] != null)
   {
       info = Request.Cookies["EmpCookies"]["EmpID"] + "</br>";
       info += Request.Cookies["EmpCookies"]["FirstName"] + "</br>";
       info += Request.Cookies["EmpCookies"]["LastName"] + "</br>";
       info += Request.Cookies["EmpCookies"]["Address"] + "</br>";

       Label1.Text = info;
   }
// cookie names are case sensitive.  Cookie named EmpCookies is different from setting a cookie named empcookies.


The above examples create a session cookie. The cookie disappears when you close your web browser. If you want to create a persistent cookie, then you need to specify an expiration date for the cookie.

Response.Cookies["message"].Expires = DateTime.Now.AddYears(1);

Limitaion of cookies

  • Cookie can store only string value.
  • Cookies are browser dependent.
  • Cookies are not secure.
  • Cookies can store small amount of data.
  • Size of cookies is limited to 4096 bytes.

Important properties of HttpCookie

  • Domain: Enables you to get or set the domain of the cookie.
  • Expires: It contains the expiration time of the cookie.
  • HasKeys: Returns bool value, indicating whether the cookie has subkeys.
  • Name: Provides the name of the cookie.
  • Path: Enables you to get or set the virtual path to submit with the cookie.
  • Secure: It contains true if the cookie is to be passed with SSL.
  • Value: It contains the value of the cookie.

Example

using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie obj = new HttpCookie("MyCookie");
        obj.Value="Welcome !!";
        Response.Cookies.Add(obj);
        string info;
        info = "Domain =: " + obj.Domain + "</br>";
        info += "Name =: " + obj.Name + "</br>";
        info += "Path =: " + obj.Path+"</br>";
        info += "Value =: " + obj.Value + "</br>";
        info += "HasKeys =: " + obj.HasKeys + "</br>";
        info += "Secure =: " + obj.Secure + "</br>";
        Label1.Text = info;
        
    }
}


Query strings

Query String object is helpful when we want to transfer a value from one page to another. Query String is very easy to use. Query string values are appended to the end of the page URL. It uses a question mark (?), followed by the parameter name followed by an equal sign (=) and its value. You can append multiple query string parameters using the ampersand (&) sign.

Always remember, we should not send lots of data through QueryString. Another limitation is that information we send through QueryString is visible on the address bar.

Example:

Response.Redirect("Default.aspx?msg="+txtMessage.Text);

In the example, the Response.Redirect method requests the Default.aspx page. The query string contains a single parameter named msg. The value for that parameter is set at run time by entering the data into textbox control. In this example the query string has one parameter but we can pass more than one parameter as given below.

Response.Redirect("Default2.aspx?ID=" + txtID.Text + "&Name=" + txtFirstName.Text);

Reading values from QueryString

Label1.Text = "ID: " + Server.HtmlEncode(Request.QueryString["ID"]) + ", Name: " + Server.HtmlEncode(Request.QueryString["Name"]);

We should use Server.HtmlEncode method while using QueryString. Server.HtmlEncode method encode the "<" sign with "<." Special characters that a Web browser cannot process, it helps to process that browser understands easily.

Important points about QueryString

  • It is easy to use.
  • Sensitive data should not pass using QueryString.
  • Browsers have 2,083-character limits on URLs. Therefore there is limit to pass the data.
  • QueryString is a part of URL.
  • It uses one or more than one parameter.
  • It uses "&" sign while using more than one parameter.
  • SPACE is encoded as '+' or '%20'