IMG-LOGO

ASP.Net State Management

andy - 16 Jul, 2013 4492 Views 0 Comment

As we know HTTP is stateless, in order to keep or store the data during web request, ASP.Net offers different type of state management that you can use to retrieve data request back when you need it. Here are the available state management you can use to store the data.

1. View State

By default, ASP.Net webform engine use View State is to store data inside a single page. If you see carefully the source code of a web form, you will see there is a hidden field that contains long string. This hidden data is actually encrypted view state value generated by ASP.Net web form engine to retain the page data properties during the postbacks. That's why when you submit a form, the data inside inputs like textboxes are still intact during the postbacks.

See below example on how to use View State in ASP.Net

protected void Page_Load(object sender, EventArgs e){
    if (!Page.IsPostBack) {
        int myCounter = 0;
        //you need to check if a viewstate is exist before getting its value
        if (ViewState["MyCounter"] != null) {
            myCounter = (int)ViewState["MyCounter"];
        } else {
            ViewState["MyCounter"] = myCounter;
        }
    }
}

2. Query String

Query String requires url to hold the temporary data. Each query string will have a unique key name with a value. What is the limitation of using Query String? Well the Query String has a limitation of string length and it must contains legal characters. In addition, it is also not secure because the url is clearly visible for users to see.

This is how you use query string.

protected void Page_Load(object sender, EventArgs e){
    if (!Page.IsPostBack) {
        string productID = "0";
        //you need to check if a query string is exist before getting its value
        if (Request.QueryString["productid"] != null) {
            productID = Request.QueryString["productid"];
        } 
    }
}

3. Session

Session allows you to store any data object types and it is only available exclusively for each user which means it is not shareable to other users. The lifetime of a session is usually 20 minutes, but it can be altered programmatically via code or by using global configuration in web config. A session can lose it's data if a timeout has been reached or the server or application pool has been restarted or user has closed and restarted their browser.

See below example on how to use session

protected void Page_Load(object sender, EventArgs e){
    if (!Page.IsPostBack) {
        int myCounter = 0;
        //you need to check if a session is exist before getting its value
        if (Session["MyCounter"] != null) {
			//You have to cast the session into integer as we save the integer into the session
            myCounter = (int)Session["MyCounter"];
        } else {
			//This is how you set the session value
            Session["MyCounter"] = myCounter;
        }
    }
}

4. Application State

Application state is used to store global objects and can be accessed by all users inside the web application. The way how it works is like Session State, the only difference is Session State is exclusively used by each unique user and the data for each user may different. While Application State will always be the same value and shareable between all users. The Application State save the data into the memory and the lifetime of this state will be ended if the server has been rebooted or the application pools have been recycled.

See below example scenario, where you want to get all the page hits available on your website. Everytime a non page postback is loaded, you want to automatically add a hit counter. On the second button click sub method, will show you how to obtain the number of page hits on your site.

protected void Page_Load(object sender, EventArgs e){
    if (!Page.IsPostBack) {
		//every time a non postback page is loaded, it will automatically add 1 value to the hit counter
        int hitCounter = 0;
        if (Application["HitCounter"] != null) {
            hitCounter = (int)Application["HitCounter"];
            hitCounter += 1;

            //we set the value again
            Application["HitCounter"] = hitCounter;
        } else {
            //we going to save the hitCounter to application state
            Application["HitCounter"] = 1;
        }
    }
}

protected void btnGetHitCounter_Click(object sender, EventArgs e) {
    int hitCounter = 0;
    if (Application["HitCounter"] != null) {
        hitCounter = (int)Application["HitCounter"];
    }
    Response.Write("Total page hits inside your website are " + hitCounter.ToString();
}

5. Cookies

Cookies is a small file that is created on user's hard drive when they access to a website. Most of the time, cookies is only used to store a simple data like string or choice preferences. For example, when you visit a website that has an option to remember your password and automatically re-login yourself when you re-visit the site. This is done via cookie. In common practice, as a programmer, you will never store any important information like password or credit card details into cookies, as they are easy to be tampered and not secure. At any time, users can clear cookies or have an option to disable their cookies on their browser. So just keep on mind about those cases when designing an online web applications.

See below code on how to use cookies in ASP.Net.

protected void btnSetCookie_Click(object sender, EventArgs e) {
        //Set Cookie for 30 days
        SetCookie("MyCookie", "This is my cookie value", 30);
    }

    protected void btnGetCookie_Click(object sender, EventArgs e) {
        Response.Write("My cookie is " + GetCookie("MyCookie");
    }

    protected void btnRemoveCookie_Click(object sender, EventArgs e) {
        //Remove cookie
        RemoveCookie("MyCookie");
    }

    //function to set a cookie 
    private void SetCookie(string cookieName, string value, int daysExpired) {
        HttpCookie cookie = new HttpCookie(cookieName);
        cookie[cookieName] = value;
        cookie.Expires = DateTime.Now.AddDays(daysExpired);
        Response.Cookies.Add(cookie);   
    }

    //function to get a cookie by speciying the cookie key
    private string GetCookie(string cookieName) {
        string value = "";
        HttpCookie cookie = Request.Cookies[cookieName];
        if (cookie != null) {
            value = cookie[cookieName];
        } 
        return value;
    }

    //we remove to cookie by specifying the key and set the expire day back to previous day
    private void RemoveCookie(string cookieName) {
        HttpCookie cookie = new HttpCookie(cookieName);
        cookie[cookieName] = "";
        cookie.Value = "";
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie);
    }

What are the differences between View State and Session State

Here is the quick list facts about their differences.

  • Session State has a timeout, while there is no timeout in View State.
  • If you want to share data between different pages, you should use Session State rather than View State, because Session State share their data as the data is saved on server memory, while View State can only access their own data via hidden field inside a single page.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Blogs

Related Tutorials