Monday 30 April 2012

Read And Write Cookies Values

Working With Cookies On Different Domains

Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier.

1)Working With Cookie Start From Initialization,Lets See How This Could Be Done

             
                HttpCookie cookie = Request.Cookies["Preferences"];
                if (cookie == null)
                {
                    cookie = new HttpCookie("Preferences");
                }
                cookie["imgforlogo"] = "~/AnyImg.png";//Filling some value in
cookie
                Response.Cookies["imgforlogo"].Expires = DateTime.Now.AddDays(-1);//Set expire time of cookie to yesterday
               //cookie.Expires = DateTime.Now.AddYears(1);                                         //Or Setting expire time of cookie to 1 year
                Response.Cookies.Add(cookie);
                string a = cookie["imgforlogo"];
                Response.Cookies["imgforlogo"].Domain = "http://www.BloggerExample.com/blogger";//Providing this cookie                                                                                                                                           value to any other subdomain  you  have                                                                                                                                              have.else you can not access cookies in                                                                                                                                          diffrent domains

                Response.Cookies["imgforlogo"].Domain = "http://localhost:60128/
blogger/";//if you want to check it  on                                                                                                                      diffrent projects on localhost



             
2)You Can Check Cookie Value On Other Page (In the same project or project on other Domain)By Providing Below Code On Page_Load or Wherever you Require
           
           HttpCookie cookie = Request.Cookies["Preferences"];           
            if (cookie == null)
            {
                      Response.Redirect("~/ErrorPage.aspx");//Redirect if there is no cookie found
            }
            else
            {
                Image1.ImageUrl = cookie["imgforlogo"];// now filling 
ImageUrl of Image1 Control with saved cookie
             }



       





No comments:

Post a Comment

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...