Thursday, June 14, 2012

Save and Retreive Cookie

Reference : http://msdn.microsoft.com/en-us/library/ms178194.aspx

MODE1: To single cookie value
STEP1: Save
          //METHOD 1
            /*
            HttpContext.Current.Response.Cookies["Test123"].Value = Name;
            HttpContext.Current.Response.Cookies["Test123"].Expires = DateTime.Now.AddDays(2);
             */
            //METHOD 2
              
            HttpCookie oCookie = new HttpCookie("Test321");
            oCookie.Value = Name;
            oCookie.Expires = DateTime.Now.AddDays(2);
            HttpContext.Current.Response.Cookies.Add(oCookie);STEP2: Retreive
//METHOD 1
            /*
            string Name = "";
            if (HttpContext.Current.Request.Cookies["Test123"] != null)
            {
                Name = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies["Test123"].Value);
            }
            return Name;
             */
            //METHOD 2
            string Name = "";
            if (HttpContext.Current.Request.Cookies["Test321"] != null)
            {
                HttpCookie oCookie = HttpContext.Current.Request.Cookies["Test321"];
                Name = HttpContext.Current.Server.HtmlEncode(oCookie.Value);
            }
            return Name;
MODE2: more than one cookie value
STEP1: Save
            HttpCookie oCookie = new HttpCookie("abc123");
            oCookie.Values["Name"] = Name;
            oCookie.Values["Pwd"] = Pwd;
            oCookie.Expires = DateTime.Now.AddDays(2);
            HttpContext.Current.Response.Cookies.Add(oCookie);
STEP2: Retreive
           string Name = "";
            string Pwd = "";
            string result = "";
            if (HttpContext.Current.Request.Cookies["abc123"] != null)
            {
                System.Collections.Specialized.NameValueCollection oCollection;
                oCollection = HttpContext.Current.Request.Cookies["abc123"].Values;

                Name = oCollection["Name"];
                Pwd = oCollection["Pwd"];
                result = "<table><tr><td>" + Name + "</td><td>" + Pwd + "</td></tr></table>";
            }
            return result;


No comments:

Post a Comment