Click here to Skip to main content
14,839,738 members
Articles / Web Development / IIS
Posted 3 Jun 2008


50 bookmarked

Cache, Session, and ViewState

Rate me:
Please Sign up or sign in to vote.
3.62/5 (28 votes)
21 Jul 2008GPL35 min read
Properly using cache, session, and viewstate objects in your application

Download - 5.08 KB

Understanding the differences between Cache, Session and ViewState

This article is originally from

This article will discuss the different types of storage methods, and which may be best for your site. As the number of web applications and developers are growing, there seems to be misunderstandings regarding what method storage method should be used, and when. There are heavy consequences which can result in loss of customers, and viewers based on incorrect strategies being used for development. Let us start, by first examining the different methods.

Understanding Cache

The Cache can be thought of as the memory. It is simply, the memory of the machine/server from which the source code is running from. This is an extremely important feature which can allow you to store difficult and complex constructed data which can be reused.

Imaging you had to query a large set of different databases, which may consist records from databases ranging from MySQL, MSSQL, to ORACLE which were joined using some VB.NET or C# code. Now if the records where changing insignificantly every couple of hours, why would we need to do a live fetch/lookup every time the user wanted to get some information? It would first be slow, and resource intensive as we would have to reconstruct all the data before displaying it to the user. By using Cache, we can store it in memory, and directly bind the data. This would be a more elegant and efficient way to retrieve data, while maintaining optimal performance.

The Cache object can also have an expiration which 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. Below is an example of how something can be put into the cache:

//Referenced from msdn

public void AddItemToCache(Object sender, EventArgs e) 
    itemRemoved = false; 
    onRemove = new CacheItemRemovedCallback(this.RemovedCallback); 
    if (Cache["Key1"] == null) 
        Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60),TimeSpan.Zero, CacheItemPriority.High, onRemove); 

public void RemoveItemFromCache(Object sender, EventArgs e) 
    if(Cache["Key1"] != null) 

Understanding Session

A session is defined as a period of time that is shared between the web application and the user. Each user that is using the web application has their own session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which 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 which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default.

A practical example would be a web application where a user logs into. Each user that logs into your system will have a unique session. We can hold additional data into the session which can be used as the user browses your site. We can hold the first name, last name, and other data simply by adding it to the session:

Session["FirstName"] = "User First Name"; 
Session["LastName"] = "User Last Name"; 

//We can clear the session variable by doing the following: 
Session["FirstName"] = null; 

//We can clear all Session variables by dong the following: 
A Session variable should be used with respect to the individual user. It stores the information on the server side and should not be taken advantage of. The difference between the cache and session is that the cache is available to be accessed from the global/application level where one reference to memory is updated. Each request will use the same cache for different users. Session variables will use different session variables for each different user. Usually a large amount of data can be stored on the session, however web sites that have a large amount of traffic usually would not use this method, as it would put a severe load on the server memory.

Understanding ViewState

ViewState is hidden data that is kept by ASP.NET pages. They track the changes to a web site during post backs. All server controls contain a view state. The control will have an EnableViewState property which will allow you to enable/disable if the control properties( e.g. Text, value, etc…) will be held in hidden fields.

The ViewState of a page can be seen if you view the source code of the running page(Right Click --> View Source). It will be listed under the following tags:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=””></input>

Having a large ViewState will cause a page to download slowly from the users side. When a user clicks on a button and a post back occurs, all the view state information has to be posted back to the server which causes a slower request. Most times this is insignificant, but imagine a person using a dial up connection. If requests, and page loading is taking a couple of minutes, most likely the user will get frustrated, and leave.

ViewState should be limited to what is needed. Most times, a label will not need to have the ViewState enabled as it will not be changing. It can even be directly written using the <span></span> tags in the html eliminating the number of bytes being sent back between post backs.

Data can also be written into the ViewState. The ViewState only persists for the life cycle of the page. If the page redirects to another page, or even to itself, the ViewState will be reset. ViewState should be used to hold small amounts of data, which will be only used on the current page. Below is an example of how we can use the ViewState:

Placing data into a ViewState:

ViewState["PreviousPage"] = ""; 

Retrieving data form ViewState:

string PreviousPage = ViewState["PreviousPage"].ToString(); 

Note: It is good practice to check if an object is null or not first. The above method can be rewritten as the following:

If (ViewState["PreviousPage"] != null ) 
    string PreviousPage = ViewState["PreviousPage"].ToString(); 

If you feel I left something out, or stated something which is incorrect, please leave me some comments. I would really appreciate it. Any suggestions will be greatly appreciated.

This article is originally from


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author

Rajib Ahmed
Web Developer ProgTalk
United States United States
C# Developer dealing with Microsoft .Net languages and frameworks. View more of my articles at Prog Talk

Comments and Discussions

QuestionAsp.Net Web Profiler Pin
easydex4-Nov-12 7:49
Membereasydex4-Nov-12 7:49 
QuestionViewState is not able to access on Page_init(), right? Pin
vicky_vicky7-Sep-10 2:00
Membervicky_vicky7-Sep-10 2:00 
AnswerMinor code improvements Pin
Andrei Ion Rînea11-Jun-08 13:46
MemberAndrei Ion Rînea11-Jun-08 13:46 
GeneralRe: Minor code improvements Pin
Rajib Ahmed16-Jun-08 12:21
MemberRajib Ahmed16-Jun-08 12:21 
GeneralAdd some source code Pin
leppie3-Jun-08 9:19
Memberleppie3-Jun-08 9:19 
GeneralRe: Add some source code Pin
Rajib Ahmed3-Jun-08 15:23
MemberRajib Ahmed3-Jun-08 15:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.