Explaining ViewState, Session and Caching in ASP.Net

Contents
  • Abstract
  • Introduction
  • ViewState
  • Session
  • Caching
  • Conclusion

Abstract

This article explains the 3s of ASP.NET; they are ViewState, Session and Caching.

Introduction

In these days, many of us are working on ASP.NET MVC, but we can't forget our classic ASP.NET and its 3-legends ViewState, Session and Caching. Let's have a look.

ViewState

ViewState is nothing but hidden data kept by ASP.Net pages in "_VIEWSTATE" as a hidden form field. They track the changes to a web site during post backs.
 
The ViewState of a page can be seen if you view the source code of the running page (right-click and select View Source). It will be listed under the following tags:
  1. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=""></input>  
Having a large ViewState will cause a page to download slowly from the user's side. When a user clicks on a button and a post-back occurs, all the view state information must be posted back to the server that causes a slower request. Usually this is insignificant, but imagine a person using a dial-up connection. If the requests and page loading is taking a couple of minutes then most likely the user will become frustrated and leave.
Please note that:
  • By default, View State is enabled for every control in the ASP.NET Framework.

  • ViewState does not hold the controls, rather it holds the values of the form controls and their corresponding IDs that would otherwise be lost due to a post-back because they do not post with the form.

  • ViewState is not used to hold session data or to transmit data between pages.

  • ViewState does not recreate the dynamically created controls of a page.

  • It does not restore the values to the controls after a post-back operation.

Session

A session is nothing but a defined period of time shared between the web application and user. Every user has an individual session. Items/Objects can be placed into the session that would only define these objects for that user. Sessions contain key variables that help to identify the related values.
 
This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application that can clear it, as well as using the timeout property in the web config file. Usually the timeout is 20 minutes by default.
 
Session Variables are stored on the server and can hold any type of data, including references. They are similar to global variables in a Windows application and use HTTP cookies to store a key with which to locate user's session variables.
 
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not need to declare a session variable or explicitly add it to the collection.
 
Let's get it clear from the following example:
  1. Session["firstName"] = "Gaurav" //User's first name  
  2. Session["lastName"] = "Arora" //User's last name  
  3. // Clear the session variable  
  4. Session["FirstName"] = null;  
  5. //Clear all Session variables  
  6. Session.Abandon();  
Please note that

By default, ASP.NET session state is enabled for all ASP.NET applications.

Caching

It's nothing but a kind of memory. In respect to ASP.Net it's the memory of the machine/server from where the source-code is running. It is one way to allow storing complex data for reusability.
 
Now think of a criteria where clients access an ASP.NET page, there are basically two ways to provide them with the information they need.
 
The ASP.NET page can either obtain information from server resources, such as from data that has been persisted to a database, or the ASP.NET page can obtain information from within the application.
 
Retrieving information from a resource outside the application will require more processing and will therefore require more time and resources on the server than if the information can be obtained from within the application space.
 
Now, suppose the information that is sent to the browsers have already been prepared. Then how is the processing of the web page faster?
 
The ASP.NET supports the following types of caching.
 
Page Output Caching 
 
Page Output Caching caches an entire page.
 
Partial Page Caching 

Partial Page Caching enables you to get around this problem by enabling you to cache only specific regions of a page.
 
DataSource Caching 

You use DataSource Caching with the various ASP.NET DataSource controls such as the SqlDataSource and ObjectDataSource controls. When you enable caching with a DataSource control, the DataSource control caches the data that it represents.
 
Data Caching 

Finally, Data Caching is the fundamental caching mechanism. Behind the scenes, all the other types of caching use Data Caching. You can use Data Caching to cache arbitrary objects in memory. For example, you can use Data Caching to cache a DataSet across multiple pages in a web application.
 
Please note that

The Cache object can also have an expiration that would allow us to reinstitute data into the memory in intervals. Using the same example as above, we can make the cache expire every two hours and repopulate the data. It would do this every 2 hours throughout the day, allowing the most up-to-date data to be fetched. The following is an example of how something can be put into the cache.
  1. public void AddItemToCache(Object sender, EventArgs e)  
  2. {  
  3. itemRemoved = false;  
  4. onRemove = new CacheItemRemovedCallback(this.RemovedCallback);  
  5. if (Cache["Key1"] == null)  
  6. Cache.Add("Key1""Value 1"null, DateTime.Now.AddSeconds(60),TimeSpan.Zero, CacheItemPriority.High, onRemove);  
  7. }  
  8. public void RemoveItemFromCache(Object sender, EventArgs e)  
  9. {  
  10. if(Cache["Key1"] != null)  
  11. Cache.Remove("Key1");  
  12. }  
Conclusion

This article explained ViewState, Session and Caching.

Up Next
    Ebook Download
    View all
    Learn
    View all