cookie的详细说明 cookie的使用 c# .net cookie购物车的实现

 

JavaScript中的另一个机制:cookie,则可以达到真正全局变量的要求。 cookie是浏览器 提供的一种机制,它将document 对象的cookie属性提供给JavaScript。可以由JavaScript对其进行控制,而并不是JavaScript本身的性质。
cookie概述
在上一节,曾经利用一个不变的框架来存储购物栏数据,而商品显示页面是不断变化的,尽管这样能达到一个模拟 全局变量的功能,但并不严谨。例如在导航框架页面内右击,单击快捷菜单中的【刷新】命令,则所有的JavaScript变量都会丢失。因此,要实现严格的 跨页面全局变量,这种方式是不行的, JavaScript中的另一个机制:cookie,则可以达到真正全局变量的要求。

cookie是浏览器提供的一种机制,它将document 对象的cookie属性提供给JavaScript。可以由JavaScript对其进行控制,而并不是JavaScript本身的性质。cookie是存于用户硬盘的一个文件,这个文件通常对应于一个域名,当浏览器再次访问这个域名时,便使这个cookie可用。因此,cookie可以跨越一个域名下的多个网页,但不能跨越多个域名使用。

不同的浏览器对cookie的实现也不一样,但其性质是相同的。例如在Windows 2000以及Windows xp中,cookie文件存储于documents and settings\userName\cookie\文件夹下。通常的命名格式为:userName@domain.txt

cookie机制将信息存储于用户硬盘,因此可以作为全局变量,这是它最大的一个优点。它可以用于以下几种场合。

(1)保存用户登录状态。例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。 cookie还可以设置过期时间,当超过时间期限后,cookie就会自动消失。因此,系统往往可以提示用户保持登录状态的时间:常见选项有一个月、三个 月、一年等。

(2)跟踪用户行为。例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。如果每次都需要选择所在地是烦琐的,当利用了 cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。因为一切都是在后 台完成,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。

(3)定制页面。如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。当用户下次访问时,仍然可以保存上一次访问的界面风格。

(4)创建购物车。正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结账的时候可以统一提交。例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。

当然,上述应用仅仅是cookie能完成的部分应用,还有更多的功能需要全局变量。cookie的缺点主要集中于安全性和隐私保护。主要包括以下几种:

(1)cookie可能被禁用。当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能;
(2)cookie是与浏览器相关的。这意味着即使访问的是同一个页面,不同浏览器之间所保存的cookie也是不能互相访问的;
(3)cookie可能被删除。因为每个cookie都是硬盘上的一个文件,因此很有可能被用户删除;
(4)cookie安全性不够高。所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。

设置cookie
每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie:

document.cookie="userId=828";
如果要一次存储多个名/值对,可以使用分号加空格(; )隔开,例如:

document.cookie="userId=828; userName=hulk";
在cookie 的名或值中不能使用分号(;)、逗号(,)、等号(=)以及空格。在cookie的名中做到这点很容易,但要保存的值是不确定的。如何来存储这些值呢?方 法是用escape()函数进行编码,它能将一些特殊符号使用十六进制表示,例如空格将会编码为“20%”,从而可以存储于cookie值中,而且使用此 种方案还可以避免中文乱码的出现。例如:

 

复制代码 代码如下:
document.cookie="str="+escape("I love ajax");

相当于:

复制代码 代码如下:
document.cookie="str=I%20love%20ajax";

当使用escape()编码后,在取出值以后需要使用unescape()进行解码才能得到原来的cookie值,这在前面已经介绍过。

尽管document.cookie看上去就像一个属性,可以赋不同的值。但它和一般的属性不一样,改变它的赋值并不意味着丢失原来的值,例如连续执行下面两条语句:

复制代码 代码如下:
document.cookie="userId=828";
document.cookie="userName=hulk";

这时浏览器将维护两个cookie,分别是userId和userName,因此给document.cookie赋值更像执行类似这样的语句:

复制代码 代码如下:
document.addCookie("userId=828");
document.addCookie("userName=hulk");

事实上,浏览器就是按照这样的方式来设置cookie的,如果要改变一个cookie的值,只需重新赋值,例如:

document.cookie="userId=929";
这样就将名为userId的cookie值设置为了929。

获取cookie的值
下面介绍如何获取cookie的值。cookie的值可以由document.cookie直接获得:

var strCookie=document.cookie;
这将获得以分号隔开的多个名/值对所组成的字符串,这些名/值对包括了该域名下的所有cookie。例如:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
document.cookie="userId=828";
document.cookie="userName=hulk";
var strCookie=document.cookie;
alert(strCookie);
//-->
</script>

从输出可知,只能够一次获取所有的cookie值,而不能指定cookie名称来获得指定的值,这正是处理cookie值最麻 烦的一部分。用户必须自己分析这个字符串,来获取指定的cookie值,例如,要获取userId的值,可以这样实现:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
//设置两个cookie
document.cookie="userId=828";
document.cookie="userName=hulk";
//获取cookie字符串
var strCookie=document.cookie;
//将多cookie切割为多个名/值对
var arrCookie=strCookie.split("; ");
var userId;
//遍历cookie数组,处理每个cookie对
for(var i=0;i<arrCookie.length;i++){
var arr=arrCookie[i].split("=");
//找到名称为userId的cookie,并返回它的值
if("userId"==arr[0]){
userId=arr[1];
break;
}
}
alert(userId);
//-->
</script>

这样就得到了单个cookie的值。

用类似的方法,可以获取一个或多个cookie的值,其主要的技巧仍然是字符串和数组的相关操作。

给cookie设置终止日期
到现在为止,所有的cookie都是单会话cookie,即浏览器关闭后这些cookie将会丢失,事实上这些cookie仅仅是存储在内存中,而没有建立相应的硬盘文件。

在实际开发中,cookie常常需要长期保存,例如保存用户登录的状态。这可以用下面的选项来实现:

document.cookie="userId=828; expires=GMT_String";
其中GMT_String是以GMT格式表示的时间字符串,这条语句就是将userId这个cookie设置为GMT_String表示的过期时间,超过这个时间,cookie将消失,不可访问。例如:如果要将cookie设置为10天后过期,可以这样实现:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
//获取当前时间
var date=new Date();
var expireDays=10;
//将date设置为10天以后的时间
date.setTime(date.getTime()+expireDays*24*3600*1000);
//将userId和userName两个cookie设置为10天后过期
document.cookie="userId=828; userName=hulk; expire="+date.toGMTString();
//-->
</script>

删除cookie
为了删除一个cookie,可以将其过期时间设定为一个过去的时间,例如:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
//获取当前时间
var date=new Date();
//将date设置为过去的时间
date.setTime(date.getTime()-10000);
//将userId这个cookie删除
document.cookie="userId=828; expire="+date.toGMTString();
//-->
</script>

指定可访问cookie的路径
默认情况下,如果在某个页面创建了一个cookie,那么该页面所在目录中的其他页面也可以访问该cookie。如果这个目录下还有子目录,则在子目录中也可以访问。例如在www.xxxx.com/html/a.html中所创建的cookie,可以被www.xxxx.com/html/b.htmlwww.xxx.com/ html/ some/c.html所访问,但不能被www.xxxx.com/d.html访问。

为了控制cookie可以访问的目录,需要使用path参数设置cookie,语法如下:

document.cookie="name=value; path=cookieDir";
其中cookieDir表示可访问cookie的目录。例如:

document.cookie="userId=320; path=/shop";
就表示当前cookie仅能在shop目录下使用。

如果要使cookie在整个网站下可用,可以将cookie_dir指定为根目录,例如:
复制代码 代码如下:
document.cookie="userId=320; path=/";

指定可访问cookie的主机名
和路径类似,主机名是指同一个域下的不同主机,例如:www.google.com和gmail.google.com就是两个不同的主机名。默认情况下,一个主机中创建的cookie在另一个主机下是不能被访问的,但可以通过domain参数来实现对其的控制,其语法格式为:

document.cookie="name=value; domain=cookieDomain";
以google为例,要实现跨主机访问,可以写为:

document.cookie="name=value;domain=.google.com";
这样,所有google.com下的主机都可以访问该cookie。

综合示例:构造通用的cookie处理函数
cookie的处理过程比较复杂,并具有一定的相似性。因此可以定义几个函数来完成cookie的通用操作,从而实现代码的复用。下面列出了常用的cookie操作及其函数实现。

1.添加一个cookie:addCookie(name,value,expireHours)
该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。这里约定expireHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。该函数实现如下:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
function addCookie(name,value,expireHours){
var cookieString=name+"="+escape(value);
//判断是否设置过期时间
if(expireHours>0){
var date=new Date();
date.setTime(date.getTime+expireHours*3600*1000);
cookieString=cookieString+"; expire="+date.toGMTString();
}
document.cookie=cookieString;
}
//-->
</script>

2.获取指定名称的cookie值:getCookie(name)
该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
function getCookie(name){
var strCookie=document.cookie;
var arrCookie=strCookie.split("; ");
for(var i=0;i<arrCookie.length;i++){
var arr=arrCookie[i].split("=");
if(arr[0]==name)return arr[1];
}
return "";
}
//-->
</script>

3.删除指定名称的cookie:deleteCookie(name)
该函数可以删除指定名称的cookie,其实现如下:
复制代码 代码如下:
<script language="JavaScript" type="text/javascript">
<!--
function deleteCookie(name){
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name+"=v; expire="+date.toGMTString();
}
//-->
</script>


 Cookie在.net中的应用

1.创建一个新的cookie,并赋值。
HttpCookie cookie;
      cookie=new HttpCookie("user");
      cookie.Domain = AppConfig.DomainName;
      cookie.Values.Add("Username",username);
      cookie.Values.Add("ldapStr",FindUserlist.Table.Rows[0]["ldapStr"].ToString());
      Response.AppendCookie(cookie);
2.获取cookie的值
 HttpCookie cookie=Request.Cookies["user"];
    if(cookie!=null)
    {
         string username = cookie["Username"];
         string ldapStr = cookie["ldapStr"];
    }
3、写Cookie 值
HttpCookie myCookie = new HttpCookie("CookieName"); 
myCookie.Values.Add("CookieItem1","CookieItem1Value"); 
myCookie.Values.Add("CookieItem2","CookieItem2Value"); 
myCookie.Expires = DateTime.Now.AddDays(30); 
Response.AppendCookie(myCookie);

4、清除Cookie值HttpCookie myCookie = HttpContext.Current.Response.Cookies["CookieObjectName"]; 
if(myCookie != null) 
myCookie.Expires = DateTime.Now;

 

 

 

js与.net后台操作Cookie

 

HttpCookie cookie = new HttpCookie("name", "ming");
HttpCookie cookie2 = new HttpCookie("pass", "123");


Response.Cookies.Add(cookie);
Response.Cookies.Add(cookie2);

 

这样写Cookie,值为:name=ming;pass=123

 

HttpCookie cookie = new HttpCookie("user");
cookie.Values.Add("name", "ming");
cookie.Values.Add("pass", "123");


HttpCookie cookie2 = new HttpCookie("user2");
cookie2.Values.Add("name2", "yu");
cookie2.Values.Add("pass2", "123");

 

Response.Cookies.Add(cookie);
Response.Cookies.Add(cookie2);

 

这样写Cookie,值为:user=name=ming&pass=123;user2=name2=yu&pass2=123

 

cookie.Expires = DateTime.Now.AddMonths(1);  //设置Cookie过期时间为一个月

 

二.写入cookie(js)

function setCookie(NameOfCookie, value, expiredays)
{
//@参数:三个变量用来设置新的cookie:
//cookie的名称,存储的Cookie值,
// 以及Cookie过期的时间.
// 这几行是把天数转换为合法的日期

var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

// 下面这行是用来存储cookie的,只需简单的为"document.cookie"赋值即可.
// 注意日期通过toGMTstring()函数被转换成了GMT时间。

document.cookie = NameOfCookie + "=" + escape(value) +
  ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

 

 

三.读取Cookie(js)

     function getCookie(name)
    {   
        var offset,cookieValue;
        var search=name+"=";
        if(document.cookie.length>0)
        {
            offset=document.cookie.indexOf(search);
            if(offset!=-1)
            {
                offset += search.length;  
                end = document.cookie.indexOf(";", offset);  
                if (end == -1)
                    end = document.cookie.length;   
                cookieValue=unescape(document.cookie.substring(offset, end));
            }
        }
        return cookieValue;
    }


    function getCookie2(objName)
    {
        var arrStr = document.cookie.split(";");
        for(var i = 0;i < arrStr.length;i ++)

       {   
            var temp = arrStr[i].split("=");   
            if(temp[0] == objName)
                return unescape(temp[1]);  
        }
    }

    function getCookie3(objName,key)
    { 
        var arrStr = document.cookie.split(";");
        for(var i = 0;i < arrStr.length;i ++){
            var temp = arrStr[i].substring(arrStr[i].indexOf(objName+"=")+objName.length+1).split("&");
            for(var j=0;j<temp.length;j++)
            {   
            var temp1=temp[j].split("=");
               if(temp1[0] == key)
                return unescape(temp1[1]);  
            }
        }
    }

注:此读法适用于多个键值对的Cookie,即写入Cookie的第二种情况。

      getCookie3("user","name");  值为ming

      getCookie3("user","pass"); 值为123

 

四.删除cookie

function delCookie(name,path){
    
var name= escape(name);
    
var expires=new Date(0);
     path
= path==""?"" :";path="+ path;
     document.cookie
= name+"="+";expires="+ expires.toGMTString()+ path;
}

 

 

.net中cookies购物车的实现  

 

1.这是用Cookie存储的购物车的几种常用的操作:
/// <summary>
/// 使用Cookie的购物车
/// </summary>
public class CookieCar {
    public const string COOKIE_CAR = "Car";     //cookie中的购物车
    /// <summary>
    /// 无参数的构造方法
    /// </summary>
    public CookieCar() {
    }
    /// <summary>
    /// 添加商品到购物车
    /// </summary>
    /// <param name="id"></param>
    /// <param name="quantity"></param>
    public void AddProductToCar(string id, string quantity) {
        string product = id + "," + quantity;
        //购物车中没有该商品
        if (!VerDictCarIsExit(id)) {
            string oldCar = GetCarInfo();
            string newCar = null;
            if (oldCar != "") {
                oldCar += "|";
            }
            newCar += oldCar + product;
            AddCar(newCar);
        }
        else {
            int count = int.Parse(GetProductInfo(id).Split(',')[1].ToString());
            UpdateQuantity(id, count + 1);
        }
    }
    /// <summary>
    /// 添加商品的数量
    /// </summary>
    /// <param name="id"></param>
    public void UpdateQuantity(string id, int quantity) {
        //得到购物车
        string products = GetCarInfo();
        products = "|" + products + "|";
        string oldProduct = "|" + GetProductInfo(id) + "|";
        if (products != "") {
            string oldCar = GetCarInfo();
            string newProduct = "|" + id + "," + quantity + "|";
            products = products.Replace(oldProduct, newProduct);
            products = products.TrimStart('|').TrimEnd('|');
            AddCar(products);
        }
    }
    /// <summary>
    /// 得到购物车
    /// </summary>
    /// <returns></returns>
    public string GetCarInfo() {
        if (HttpContext.Current.Request.Cookies[COOKIE_CAR] != null) {
            return HttpContext.Current.Request.Cookies[COOKIE_CAR].Value.ToString();
        }
        return "";
    }
    /// <summary>
    /// 根据ID得到购物车中一种商品的信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private string GetProductInfo(string id) {
        string productInfo = null;
        //得到购物车中的所有商品
        string products = GetCarInfo();
        foreach (string product in products.Split('|')) {
            if (id == product.Split(',')[0]) {
                productInfo = product;
                break;
            }
        }
        return productInfo;
    }
    /// <summary>
    /// 加入购物车 
    /// </summary>
    private void AddCar(string product) {
        HttpCookie car = new HttpCookie(COOKIE_CAR, product);
        car.Expires = DateTime.Now.AddDays(7);
        HttpContext.Current.Response.Cookies.Remove(COOKIE_CAR);
        HttpContext.Current.Response.Cookies.Add(car);
    }
    /// <summary>
    /// 判断商品是否存在
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private bool VerDictCarIsExit(string id) {
        //存在的标志: true 有, false 没有
        bool flag = false;
        //得到购物车中的所有商品
        string products = GetCarInfo();
        foreach (string product in products.Split('|')) {
            if (id == product.Split(',')[0]) {
                flag = true;
                break;
            }
        }
        return flag;
    }
    /// <summary>
    /// 通过商品编号删除订单
    /// </summary>
    /// <param name="id"></param>
    public void DeleteProduct(string id) {
        string oldProduct = GetProductInfo(id);
        oldProduct = "|"+oldProduct+"|";
        string products = GetCarInfo();
        if(products != "") {
            products = "|"+products+"|";
            products = products.Replace(oldProduct, "|");
            products = products.TrimStart('|').TrimEnd('|');
            AddCar(products);
        }
    }
    /// <summary>
    /// 晴空购物车
    /// </summary>
    public void ClearCar() {
        AddCar("");
    }
    /// <summary>
    /// 确认订单
    /// </summary>
    public void ConfirmOrder(System.Web.UI.Page page, double orderTotalPrice, User user) {
        //得到订单信息
        string products = GetCarInfo();
        if (products != "") {
            string message =null;
            if (ProductManager.OrderConfirm(products, orderTotalPrice, user, out message)) {
                ClearCar();
            }
            Javascript.Alert(page, message, "Default.aspx");
        }
        else {
            Javascript.Alert(page, "订单为空,请选择商品!", "ProductList.aspx");
        }
    }
}
/// <summary>
    /// 得到购物车数据
    /// </summary>
    public DataSet GetCarData(GridView gv) {
        string carInfo = new CookieCar().GetCarInfo();
        if (carInfo != "") {
            string sql = "";
            foreach (string product in carInfo.Split('|')) {
                int id = int.Parse(product.Split(',')[0].ToString());
                int buyCount = int.Parse(product.Split(',')[1].ToString());
                if (sql != "") {
                    sql += " union ";
                }
                sql += "select *, " + buyCount + " as buyCount, Price*" + buyCount + " as totalPrice from Products where Id = " + id;
            }
            TotalPrice(gv);       //计算总价
            return ProductManager.GetCarBySql(sql);
        }
        else {
            Javascript.GoError("购物车为空,请选择商品!");
        }
        return null;
    }
    /// <summary>
    /// 计算总价
    /// </summary>
    public double TotalPrice(GridView gv) {
        double totalCarPrice = 0d;
        foreach (GridViewRow row in gv.Rows) {
            int rowIndex = row.RowIndex;
            double totalPrice = double.Parse((gv.Rows[rowIndex].FindControl("lblTotalPrice") as Label).Text.ToString());
            totalCarPrice += totalPrice;
        }
        return totalCarPrice;
    }

 

 

.net c#购物车模块分析

 

  购物车的实现形式多样,在这里,我用到了虚拟表和sesson方法存储。
    首先创建一个商品的表,GridView控件绑定数据源。在GridView中添加一个列,控件为
buttonfield.在GridView的RowCommand事件写代码:
         DataTable cart new DataTable();//新建虚拟表
        if (Session["shoppingcart"] == null)
        {
            cart.Columns.Add("pname", typeof(string));//编辑表的列的属性
            cart.Columns.Add("pid", typeof(string));
            cart.Columns.Add("price", typeof(string));
            Session["shoppingcart"] cart;
        }
        cart (DataTable)Session["shoppingcart"];
        int Convert.ToInt32(e.CommandArgument);
      string p1 GridView1.Rows[n].Cells[0].Text;//获得商品的数据
      string p2 GridView1.Rows[n].Cells[1].Text;
      string p3 GridView1.Rows[n].Cells[2].Text;
        DataRow rr cart.NewRow();
        rr["pname"] p1;
        rr["pid"] p2;
        rr["price"] p3;
        cart.Rows.Add(rr);//增加一条记录
        
        Session["shoppingcart"] cart;
购物车页面:添加一个未绑定数据源的GridView控件:一个显示总额的lable的控件。
在页面加载事件中写代码:
if (!this.IsPostBack){
        GridView1.DataSource Session["shoppingcart"];
        GridView1.DataBind();
        double sum 0.0;
        for (int 0; GridView1.Rows.Count; i++)
        {
           
         sum sum (double.Parse(GridView1.Rows.Cells[2].Text));
           
        }
        Label2.Text ="总计:"+ sum.ToString()+"元";
        }
这样显示GridView控件了虚拟表的数据并且把总共的金额进行了加总。
增添两个按钮控件:清空   提交订单
清空按钮代码:

        Session.Remove("shoppingcart");
        GridView1.DataBind();
        Label2.Text "总计:0元";
提交订单:这里是提交给数据库,建一个订单表。
事件代码:
        string name Session["sa"].ToString();//获得提交用户的用户名
        double sum 0.0;
        string p1="";
        string p2="";
        for (int 0; GridView1.Rows.Count; i++)
        {
         sum sum (double.Parse(GridView1.Rows
.Cells[2].Text));
          p1 =p1+"、" GridView1.Rows.Cells[0].Text;
          p2 =p2 +"、"+ GridView1.Rows
.Cells[1].Text;
           }
        
        DataClasses3DataContext new DataClasses3DataContext();
        dingdan dan new dingdan();
        dan.username name;
        dan.dingdan1= p1+p2;
        dan.price sum.ToString();
        dan.addtime Convert.ToDateTime(DateTime.Now);
        w.dingdans.InsertOnSubmit(dan);
        w.SubmitChanges();
点击清空:

提交订单后,订单查看:

 这里的还很粗糙,代码很多需要完善。

 

.Net用Cookie做购物车

public class ShoppingCart
    {
       //保存购物车ID和数量到Cookie中

//保存ID的格式:"1,32,43

//下面是对应数量:"2,3,2"

如ID=1,对应的数量就是2
       public void SaveCookieCart(int productId, int amount)
       {
        
           if (HttpContext.Current.Request["ShoppingCart"]== null)
           {
               HttpCookie cookie = new HttpCookie("ShoppingCart");
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);

               cookie.Values.Add("ProductId",productId.ToString());
               cookie.Values.Add("Amount", amount.ToString());
               HttpContext.Current.Response.AppendCookie(cookie); cookie.Expires = dt.Add(ts);
           }
           else
           {
               //用逗号隔开
               HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] Amount = HttpContext.Current.Request.Cookies["ShoppingCart"]["Amount"].ToString().Split(',');
               if (!ProductIdArray.Contains(productId.ToString()))
               {
                   cookie.Values["ProductId"] = HttpContext.Current.Request.Cookies["ShoppingCart"]["ProductId"] + "," + productId;
                   cookie.Values["Amount"] = HttpContext.Current.Request.Cookies["ShoppingCart"]["Amount"] + "," + amount;
                
                 HttpContext.Current.Response.AppendCookie(cookie);
                   DateTime dt = DateTime.Now;
                   TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
                   cookie.Expires = dt.Add(ts);
             
           }
       }
       //购物车数据源,也可以作为订单数据源
       public IList<Model.ShoppingCartProduct> GetIListShoppingCartFromCookie()
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
               int productId;
               int amount;
               IList<Model.ShoppingCartProduct> iList = new List<Model.ShoppingCartProduct>();
               for (int i = ProductIdArray.Length-1; i >= 0; i--)
               {
                   productId = Convert.ToInt32(ProductIdArray[i]);
                   amount = Convert.ToInt32(AmountArray[i]);
                   Model.ShoppingCartProduct shoppingCart = new SqlDAL.ShoppingCart().GetShoppingCartItem(productId,amount);
                   iList.Add(shoppingCart);           
               }
               return iList;
           }
           else{
               return null;          
           }
       }
       //删除购物车中的某一项
       public void DeleteShoppingCartCookieItem(int productId)
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
         
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
                             StringBuilder productIdCookie=new StringBuilder();
               StringBuilder amountCookie = new StringBuilder();
               for (int i =0; i<ProductIdArray.Length; i++)
               {
                   string productIdItem=ProductIdArray[i].Trim();
                   string amountItem=AmountArray[i].Trim();
                   //如果不相等就保存
                   if(productId.ToString()!=productIdItem){  
                      
                 
                   productIdCookie.Append(productIdItem+",");//追加完成
                   amountCookie.Append(amountItem+",");//追加完成
                   }
               }
                 //更新删除Id后的COOKIE
                   cookie.Values["ProductId"] = productIdCookie.ToString().Substring(0, productIdCookie.Length-1);
                   cookie.Values["Amount"] =amountCookie.ToString().Substring(0,amountCookie.Length-1);
                   HttpContext.Current.Response.AppendCookie(cookie);
                   DateTime dt = DateTime.Now;
                   TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
                   cookie.Expires = dt.Add(ts);

           }
       }
       //清空购物车
       public void ClearCookie()
       {

           if (HttpContext.Current.Request["ShoppingCart"] != null)
           {
               HttpCookie cookie = new HttpCookie("ShoppingCart");
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(0, 0, 0, 0, 0);
               cookie.Values.Add("ProductId", "");
               cookie.Values.Add("Amount", "");
               HttpContext.Current.Response.AppendCookie(cookie); cookie.Expires = dt.Add(ts);
           }

       }
       //修改购物车某商品的数量
       public void ModifyAmount(int productId,int amount)
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
             
               StringBuilder productIdCookie = new StringBuilder();
               StringBuilder amountCookie = new StringBuilder();
               for (int i = 0; i < ProductIdArray.Length; i++)
               {
                 
                   //如果不相等就保存
                   if (productId.ToString()==ProductIdArray[i].ToString())
                   {


                       productIdCookie.Append(ProductIdArray[i]+ ",");
                       amountCookie.Append(amount + ",");//修改操作
                   }
                   else
                   {
                       productIdCookie.Append(ProductIdArray[i] + ",");//追加完成
                       amountCookie.Append(AmountArray[i] + ",");//追加完成
                   }
               }
               //更新删除Id后的COOKIE
               cookie.Values["ProductId"] = productIdCookie.ToString().Substring(0, productIdCookie.Length - 1);
               cookie.Values["Amount"] = amountCookie.ToString().Substring(0, amountCookie.Length - 1);//删除最后的逗号
               HttpContext.Current.Response.AppendCookie(cookie);
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
               cookie.Expires = dt.Add(ts);
         
           }
          
       }


    }
}

 

.netc#购物车 代码系列3
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Data; 
using DAO; 
using System.Drawing; 
public partial class ShoppingCart : System.Web.UI.Page 

    //整型变量,用于存储总金额  
    private Int32 Total = 0; 
    protected void Page_Load(object sender, EventArgs e) 
   
        if (!IsPostBack) 
       
            BindCartList(); 
       
   
    private void BindCartList() 
   
        DataTable dt = new DataTable(); 
        //如果Session变量存在,则直接获取  
        if (Session["Cart"] != null) 
       
            dt = (DataTable)Session["Cart"]; 
       
        else//如果Session变量不存在,创建存储数据的表结构  
       
            dt.Columns.Add(new DataColumn("ID", typeof(Int32))); 
            dt.Columns.Add(new DataColumn("ProductNo", typeof(String))); 
            dt.Columns.Add(new DataColumn("ProductName", typeof(String))); 
            dt.Columns.Add(new DataColumn("BuyPrice", typeof(String))); 
            dt.Columns.Add(new DataColumn("Amount", typeof(Int32))); 
       
        //ID或ProductNo不为null  
        //则表示选中一件商品添加到购物车  
        if (ID != null) 
       
            //先判断购物车中是否已经存在该商品  
            Boolean IsExist = false; 
            foreach (DataRow dr in dt.Rows) 
           
                if (dr["ProductNo"].ToString() == ProductNo) 
               
                    IsExist = true; 
                    break; 
               
           
            //如果购物车中存在该商品,则提示客户  
            //该商品不会被重复添加到购物车  
            if (IsExist) 
           
                ScriptManager.RegisterStartupScript( 
                    this, typeof(Page), "alertExist", "alert('您选择的商品(编号:" + ProductNo + ")已在购物车存在!')", true); 
           
            else//如果购物车中不存在该商品,则添加到购物车  
           
                SqlHelper helper = new SqlHelper(); 
                DataTable dtRow = helper.FillDataTable( 
                    String.Format("Select * From Products Where ID={0}", ID.ToString())); 
                dt.Rows.Add(new object[]{ 
                    Convert.ToInt32(ID.ToString()), 
                    dtRow.Rows[0]["ProductNo"].ToString(), 
                    dtRow.Rows[0]["ProductName"].ToString(), 
                    Convert.ToInt32(dtRow.Rows[0]["BuyPrice"].ToString()), 
                    1}); 
           
       
        gvCart.DataSource = dt; 
        gvCart.DataBind(); 
        Session["Cart"] = dt; 
   
    protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e) 
   
        if (e.Row.RowType == DataControlRowType.DataRow) 
       
            //GridView行的加亮显示功能  
            e.Row.Attributes.Add("onmouseover", "b=this.style.backgroundColor;this.style.backgroundColor='#E1ECEE'"); 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=b"); 
            //给+号图片和-号图片添加客户端click事件  
            //用JavaScript实现数量的+1和-1  
            TextBox tb = (TextBox)e.Row.FindControl("txtAmount"); 
            ((HtmlImage)e.Row.FindControl("imgReduce")).Attributes.Add("onclick", "Reduce(" + tb.ClientID + ")"); 
            ((HtmlImage)e.Row.FindControl("imgPlus")).Attributes.Add("onclick", "Plus(" + tb.ClientID + ")"); 
             
            //根据商品单价和数量计算购物车中商品的总金额  
            DataRowView drv = (DataRowView)e.Row.DataItem; 
            Total += Int32.Parse(drv["BuyPrice"].ToString())*Int32.Parse(tb.Text); 
       
        if (e.Row.RowType == DataControlRowType.Footer) 
       
            //将总金额显示在金额一列对应的Footer单元格  
            e.Row.Cells[1].Text = "金额总计:"; 
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right; 
            e.Row.Cells[2].Text = Total.ToString("c2"); 
            e.Row.Cells[2].ForeColor = Color.Red; 
       
   
    protected void gvCart_RowDeleting(object sender, GridViewDeleteEventArgs e) 
   
        //点击删除时从DataTable中删除对应的数据行  
        if (Session["Cart"] != null) 
       
            DataTable dt = (DataTable)Session["Cart"]; 
            dt.Rows.RemoveAt(e.RowIndex); 
            dt.AcceptChanges(); 
            Session["Cart"] = dt; 
            Response.Redirect("ShoppingCart.aspx"); 
       
   
    protected void imgbtnTotal_Click(object sender, ImageClickEventArgs e) 
   
        //遍历GridView,根据每行的文本框中的值  
        //修改DataTable中对应行中数量一列的值  
        if (Session["Cart"] != null) 
       
            DataTable dt = (DataTable)Session["Cart"]; 
            for (int i = 0; i < gvCart.Rows.Count; i++) 
           
                dt.Rows[i]["Amount"] = ((TextBox)gvCart.Rows[i].FindControl("txtAmount")).Text; 
           
            dt.AcceptChanges(); 
            Session["Cart"] = dt; 
            Response.Redirect("ShoppingCart.aspx"); 
       
   
    #region 属性  
    /// <summary>  
    /// get URL参数ID的值,定义为Nullable<Int32>类型  
    /// </summary>  
    private Int32? ID 
   
        get 
       
            try 
           
                return Int32.Parse(Request.QueryString["ID"]); 
           
            catch 
           
                return null; 
           
       
   
    /// <summary>  
    /// get URL参数ProductNo的值  
    /// </summary>  
    private String ProductNo 
   
        get 
       
           return Request.QueryString["ProductNo"]; 
       
   
    #endregion  

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值