What are cookies? (ASP.NET interview questions)
- By Shiv Prasad Koirala in ASP.NET
- Mar 22nd, 2014
- 9528
- 0
This ASP.NET interview question is taken from the famous .NET interview question book written by shivprasadkoirala and published by Bpb publication. Below is the link to flipkart for more details on the .NET interview question book
http://www.flipkart.com/net-interview-questions-cd-rom-6th/p/itmdyuqzdqx8cvqx
Cookies are data which are stored in small text files on the end users machine. These files have information about users who are returning to your website. We can store the following type of information in cookies:-
- Track how many times the user is coming to your site.
- Which part of the site he visits most?. So depending on which section he visits more you can show him those section first when he comes to the site.
To set a cookie using JavaScript we need to use the document object and we need to call the cookie property as shown in the below code.
document.cookie="pagevisited=news"; // cookie 1
document.cookie="name=shiv"; // cookie 2
To display the cookie back we can just write the below code.
alert(document.cookie)";
If we have multiple cookies set we will get the value in name and value pair with semicolon separated as shown in the below sample.
cookie1=value; cookie2=value;
There are two kinds of cookies permanent cookie and temporary cookie.
Permanent cookies are those which do not have expiry date and they are stored forever. The only way to delete these kinds of cookies is by going the browser and clearing cookies.
The second types of cookies have expiry date attached to it. So as soon as the date is surpassed the browser deletes that cookie. Below is a simple code which shows how to create a cookie with an expiry date.
document.cookie="visited=aboutus; expires=Mon, 12 Dec 2015 12:00:00 GMT";
If you already have a cookie and you want to delete it by javascript then just set the date to back old date. For example in the below cookie we have set the date to 1990 which will inform the browser to delete this cookie.
document.cookie="visited=aboutus; expires=Mon, 12 Dec 1990 12:00:00 GMT";
Below is a simple real time example of counter which tracks using cookies how many times the user has visited the site. In the below code we first read the cookie counter , increment the counter value and store that counter value back to the cookie.
var counter = document.cookie; // read the counter
counter = counter + 1; // increment the counter
document.cookie = "counter=" + counter; // save the counter in cookie
One very connected ASP.NET interview questions which is asked around session management is difference between session and viewstate. Below is a great demonstrative videos created by www.questpond.com worth as watch.
Shiv Prasad Koirala
Visit us @ www.questpond.com or call us at 022-66752917... read more