Using Cookie

using System;
using System.Data;
using System.Configuration;using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class   _Default :System.Web.UI.Page{
  protected void Page_Load(object sender, EventArgs e){
   //in case, it’s already there..
Response.Cookies.Remove(“myCookie”);
Response.Cookies.Add(new HttpCookie(“myCookie”,“It’s Cookie!”));
  }
}
<%@ Page Language=”C#”AutoEventWireup=”true” 
CodeFile=”Default.aspx.cs”Inherits=”_Default” %>

<!DOCTYPE  html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title><script language=”javascript”type=”text/javascript”>
<!–

function Button1_onclick() {
  alert(readCookie(“myCookie”)); 
}

/*
 * JavaScript - Cookie Library 
 * Ref     : http://www.quirksmode.org/js/cookies.html
 * Comment : The following codes can be put in the seperated 
 *           js file.  */
function readCookie(name)
{
  var nameEQ = name + “=”;
  var ca = document.cookie.split(‘;’);
  for(var i=0;i <ca.length;i++){
    var c = ca&#91;i&#93;;
    while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
     if (c.indexOf(nameEQ) == 0) 
        return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name)
{
  createCookie(name,“”,-1);
}

function createCookie(name,value,days)
{
 if (days){
    var date =  new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    var expires =  “; expires=” +date.toGMTString();
 }
 else var expires = “”;br> document.cookie = name +  “=” + escape(value) +
            expires +  “;path=/”;
}

// –>
</script>
</head>
<body>
 <form id=”form1″runat=”server”>
  <div>
   <inputid=”Button1″type=”button”value=”Read Cookie”
     language=”javascript”onclick=”return Button1_onclick()” /></div>
  </form>
</body></html>

Posted in ASP.NET, JavaScript.

One thought on “Using Cookie

Leave a Reply

Your email address will not be published. Required fields are marked *