Thursday, 29 March 2012

asp.net cookie example: how to create a cookie asp.net cookie example: how to create a cookie

  1. <%@ Page Language="C#" %>  
  2. <%@ Import Namespace="System.Net" %>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5.   
  6. <script runat="server">  
  7.     protected void Page_Load(object sender, System.EventArgs e) {  
  8.         HttpCookie userCookie = new HttpCookie("UserInfo");  
  9.         userCookie["Country"] = "Italy";  
  10.         userCookie["City"] = "Rome";  
  11.         userCookie["Name"] = "Jones";  
  12.         userCookie.Expires = DateTime.Now.AddDays(3);  
  13.         Response.Cookies.Add(userCookie);  
  14.         Label1.Text = "Cookie create successful!<br><br/>";  
  15.           
  16.         HttpCookie cookie = Request.Cookies["UserInfo"];  
  17.           
  18.         if (cookie != null)   
  19.         {  
  20.             string country = cookie["Country"];  
  21.             string city = cookie["City"];  
  22.             string name = cookie["Name"];  
  23.             Label2.Text = "Cookie Found and read<br/>";  
  24.             Label2.Text += "Name: " + name;  
  25.             Label2.Text += "<br />Country: " + country;  
  26.             Label2.Text += "<br />City: " + city;  
  27.         }  
  28.     }  
  29. </script>  
  30.   
  31. <html xmlns="http://www.w3.org/1999/xhtml">  
  32. <head runat="server">  
  33.     <title>asp.net cookie example: how to create a cookie</title>  
  34. </head>  
  35. <body>  
  36.     <form id="form1" runat="server">  
  37.     <div>  
  38.         <h2 style="color:Teal">asp.net Cookie example: Create a cookie</h2>  
  39.         <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="SeaGreen">  
  40.         </asp:Label>  
  41.         <asp:Label ID="Label2" runat="server" Font-Size="Large" ForeColor="Crimson">  
  42.         </asp:Label>  
  43.     </div>  
  44.     </form>  
  45. </body>  
  46. </html>   
  47.  

  48.  
  49.  
  50.  
  51.  
Post a Comment