Tuesday, January 13, 2009

Reading from Cookies

Cookies are a nice feature to store data in client side so that we can manage the state in the client side.

Reading from Cookies


protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.Cookies["Theme"] == null)
{
Response.Cookies["Theme"].Value = "ThemeName";
Response.Cookies["Theme"].Expires = DateTime.Now.AddDays(2);
}
else
this.Theme = Request.Cookies["Theme"].Value.ToString();
}

1 comments:

Abhijeet said...

Cookies are small files which are sent along with the pages. This is a commonly used clientside state management method. this is how we set cookies.

HttpCookie cookieName = new HttpCookie("myCookie");
cookieName .Expires = DateTime.Now.AddMinutes(60); Response.Cookies.Add(cookieName);

To delete cookies logically we make a cookie with the same name and set the expiration time to a date earlier than today. When the browser checks the cookie's expiration, the browser will discard the now-outdated cookie.

HttpCookie cookieName = new HttpCookie("myCookie");
cookieName .Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookieName);

Post a Comment