Friday, April 13, 2012

ASP.NET: Get/Set value from/to cookies

string cookieName;
private int CookieValue
    {
        get
        {
            int _intValue =0;
            if(Request.Cookies[cookieName] != null)
                int.TryParse(Request.Cookies[cookieName].Value, out _intValue);

            return _intValue;
        }
        set
        {
            if(Request.Cookies[cookieName] != null)
                Response.Cookies.Add(new HttpCookie(cookieName, Convert.ToString(value)));
            else
                Response.Cookies["cookieName"].Value = Convert.ToString(value);
        }
    }

Storing multiple values in cookies

Response.Cookies[cookieName]["age"] = 16;
Response.Cookies[cookieName]["Name"] = "John";
Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(1);


No comments:

Post a Comment