asp.net 之 购物车

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpCookie hc = null;
        if (Response.Cookies["shop"] == null)
        {
            hc = new HttpCookie("shop");
            
        }
        else 
        {
            hc = Request.Cookies["shop"];
            
        }

        //添加购物车

        //判断商品是否存在
        bool isExistgood = false;
        if (hc.Values.Count > 0) 
        {
            foreach (string vname in hc.Values) 
            {
                if (vname == this.TextBox1.Text.Trim()) 
                {
                    //购物车有东西
                    isExistgood = true;
                    break;

                }
            }
        }
     
        if (isExistgood)
        {
          
            //购物车里有这个商品了,数量加1;
            int num = Int32.Parse(hc.Values[this.TextBox1.Text.Trim()]);
            num++;
            hc.Values.Remove(hc.Values[this.TextBox1.Text.Trim()]);
       
            hc.Values.Set(this.TextBox1.Text.Trim(), num.ToString());
        }
        else 
        {
            //购物u车没有商品添加
           // hc["num"] = "1";
           // hc.Values.Set(this.TextBox1.Text.Trim(), "1");
            hc.Values.Set(this.TextBox1.Text.Trim(), "1");
        }

        hc.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(hc);

        this.Label1.Text = "";
        foreach (string vname in hc.Values) 
        {
            this.Label1.Text += "商品:" + vname + "数量:" + hc[vname];
        }

       
        
    }
}

  

原文地址:https://www.cnblogs.com/mengluo/p/6008244.html