ListInfo.aspx向购物车的添加商品的方法
private void GouWu(string name, double price, string id)
{
//往购物车中添加商品
HttpCookie hc = null;
if (Request.Cookies["ShoppingCart"] == null)
{
//如果Cookies中不存在ShoppingCart,则创建
hc = new HttpCookie("ShoppingCart");
}
else
{
//如果Cookies中存在ShoppingCart,则取出
hc= Request.Cookies["ShoppingCart"];
}
bool flag=true;//标记在购物车中是否存在本次选择的物品
//在购物车的Cookies中查找是否存在这次要选择的物品
foreach (string item in hc.Values)
{
if (item == id)
{
flag = false;
break;
}
}
if (flag)
{
//如果选择的内容在购物车中没有,则创建一个新的子键
hc.Values.Add(id, id + "|" + name + "|" + price + "|" + 1 + "|");
}
else
{
//如果选择的内容在购物车中没,则删除原来的,添加一个新的
int num = int.Parse(hc.Values[id].Split(new char[] { '|' })[3]) + 1;
hc.Values.Remove(id);
hc.Values.Add(id,id + "|" + name + "|" + price + "|" + num + "|");
}
hc.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(hc);
Response.Redirect("ShoppingCart.aspx");
}
在ShoppingCart.aspx页面的Load事件中
List<ShoppingCart> list = new List<ShoppingCart>();
//循环从购物车中取出物品添加到集合
foreach (string item in Request.Cookies["ShoppingCart"].Values)
{
if (item != null)
{
char[] sp = { '|' };
string[] w = Request.Cookies["ShoppingCart"][item].Split(sp);
ShoppingCart gwc = new ShoppingCart();
gwc.Id = w[0];
gwc.Name = w[1];
gwc.Price = int.Parse(w[2]);
gwc.Number = int.Parse(w[3]);
list.Add(gwc);
}
}
GridView1.DataSource = list;
GridView1.DataBind();
ShoppingCart类代码
public class ShoppingCart
{
public ShoppingCart()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
string name;
public string Name
{
get { return name; }
set { name = value; }
}
double price;
public double Price { get { return price; } set { price = value; } }
string id;
public string Id { get { return id; } set { id = value; } }
int number;
public int Number { get { return number; } set { number = value; } }
}