Creating cookies with ASP.NET is simple and straight forward. The System.Web namespace offers a class called HttpCookie to create cookies. A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. A Web server sends you a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced.
The following code demonstrates the creation of cookies.
protected void CreateCookie_Click(object sender, EventArgs e){
HttpCookie newCookie= new HttpCookie("Books");
newCookie.Values.Add("Name", TextBox1.Text);
newCookie.Values.Add("FavBook", RadioButtonList1.SelectedItem.Text);
newCookie.Expires = Convert.ToDateTime("12/31/2009");
Response.Cookies.Add(newCookie);
Label3.Text = "Cookie Created";
Select.Visible = false;
TextBox1.Visible = false;
Label1.Visible = false;
Label2.Visible = false;
RadioButtonList1.Visible = false;
}
To ensure that the cookie stays on the user's hard drive for a while we set it's date using the HttpCookie object's Expires property. To get this cookie sent back to the browser and stored on the hard drive we used the Response object.
Retriving the cookie
The code below demonstrates how to retrieve a cookie and display information to the user based on his preferences.
protected void RetrieveCookie_Click(object sender, EventArgs e){
Label3.visible=false;
Label4.Text = "Hello" +" "+ Request.Cookies["Books"]["Name"] + "."+
"We have a new book for you:";
if(Request.Cookies["Books"]["FavBook"] == "VB")
Label5.text="XYZ VB Book";
else if( Request.Cookies["Books"]["FavBook"] == "C#")
Label5.text="ABC C# Book";
else
Label5.text="Arif's ASP Book";
}
The path to the location on the hard drive where cookies are stored is C:\Documents and Settings\Administrator\Cookies.
No comments:
Post a Comment