实现一个用Cookie做的购物车

liyuan_accp 2010-09-07 04:38:03
我们现在在做一个商务网站,类似与淘宝,现在需要用Cookie做一个购物车,希望哥哥姐姐们有这方面的资料,最好是有这方面的例子可以在电脑上运行的那种例子,如果谁有的话希望发一个或者给一个链接地址,我的 QQ:593248154,希望大家能够帮忙一下,小弟在这里说谢谢啦!
...全文
812 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
胡晗梦想 2012-02-10
  • 打赏
  • 举报
回复
请问 jayinIT, 那个box参数是什么啊
porschev 2010-09-09
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jayinit 的回复:]
经典cookies购物车
[/Quote]

这都能翻出来。。。
liyuan_accp 2010-09-09
  • 打赏
  • 举报
回复
protected void Page_Load(object sender, EventArgs e)
{
int ProID;
HttpCookie cookie;
bool Tempbl = false;
string Tempstr;
string old="";
int c = 0;
if (!Page.IsPostBack)
{
if (!object.Equals(Request.QueryString["id"], null))
{
ProID = int.Parse(Request.QueryString["id"]);
//创购物车cookie yxy .//sql8.net
if (object.Equals(Request.Cookies["ztbscart"], null))
cookie = new HttpCookie("ztbscart");
else
cookie = Request.Cookies["ztbscart"];
//判断是否已存在于购物车内 yxy // sql8.net
for (int i = 0; i < cookie.Values.Keys.Count; i++)
{
if (!object.Equals(cookie.Values.Keys[i], null))
{
Tempstr = cookie.Values.AllKeys[i].ToString();
if (Tempstr.Trim() != "")
{
if (ProID == int.Parse(cookie.Values.AllKeys[i]))
{
Tempbl = true;
old = cookie.Values[i];
c = i;
break;
}
}
}
}
//不未购买过则加入购物车 yxy //sql8.net
if (!Tempbl)
cookie.Values.Add(ProID.ToString(), "1");
else
{
// 怎么在这个地方对购物车已存在的商品数量进行加+1呀,我试了几下都没有试出来
}
TimeSpan ts = new TimeSpan(0, 0, 10, 0);
cookie.Expires = DateTime.Now + ts;
Response.AppendCookie(cookie);

}
BindGrid();
}
liyuan_accp 2010-09-09
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using Model;
public partial class AddToCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int ProID;
HttpCookie cookie;
bool Tempbl = false;
string Tempstr;
string old="";
int c = 0;
if (!Page.IsPostBack)
{
if (!object.Equals(Request.QueryString["id"], null))
{
ProID = int.Parse(Request.QueryString["id"]);
//创购物车cookie yxy .//sql8.net
if (object.Equals(Request.Cookies["ztbscart"], null))
cookie = new HttpCookie("ztbscart");
else
cookie = Request.Cookies["ztbscart"];
//判断是否已存在于购物车内 yxy // sql8.net
for (int i = 0; i < cookie.Values.Keys.Count; i++)
{
if (!object.Equals(cookie.Values.Keys[i], null))
{
Tempstr = cookie.Values.AllKeys[i].ToString();
if (Tempstr.Trim() != "")
{
if (ProID == int.Parse(cookie.Values.AllKeys[i]))
{
Tempbl = true;
old = cookie.Values[i];
c = i;
break;
}
}
}
}
//不未购买过则加入购物车 yxy //sql8.net
if (!Tempbl)
cookie.Values.Add(ProID.ToString(), "1");
else
{
//HttpCookie cookienew = new HttpCookie("ztbscart");


//string newstr = (int.Parse(old) + 1).ToString();
//if (newstr == "")
//{
// newstr = "0";
//}
//cookienew.Values.Add(ProID.ToString(), newstr);
//TimeSpan ts1 = new TimeSpan(0, 0, 10, 0);
//cookienew.Expires = DateTime.Now + ts1;
//Response.AppendCookie(cookienew);
//string newstr = (int.Parse(old) + 1).ToString();
//string repstr=cookie.Values[c].Replace(old, newstr);

//int temp=0;
//for (int i = 0; i < GridView1.Rows.Count; i++)
//{
// if (c == i)
// {
// temp = int.Parse(cookie.Value[c].ToString()) + 1;
// }
//}
//cookie.Values.Add(ProID.ToString(), temp.ToString());
}
TimeSpan ts = new TimeSpan(0, 0, 10, 0);
cookie.Expires = DateTime.Now + ts;
Response.AppendCookie(cookie);

}
BindGrid();
}
}

/// <summary>
/// 修改商品数量
/// </summary>
/// <param name="id">商品ID</param>
/// <param name="quantity">数量</param>
private int UpdateQuantity(int id)
{
return id++;
}
//绑定数据 yxy //sql8.net
private void BindGrid()
{
DataTable MyDt;
DataRow MyDr;
string str = "";
MyDt = new DataTable();
MyDt.Columns.Add(new DataColumn("id", str.GetType()));
MyDt.Columns.Add(new DataColumn("Title", str.GetType()));
MyDt.Columns.Add(new DataColumn("Num", str.GetType()));
MyDt.Columns.Add(new DataColumn("Price", str.GetType()));
MyDt.Columns.Add(new DataColumn("Discount", str.GetType()));
MyDt.Columns.Add(new DataColumn("Vipprice", str.GetType()));
MyDt.Columns.Add(new DataColumn("Totle", str.GetType()));
if (!object.Equals(Request.Cookies["ztbscart"], null))
{
HttpCookie cookie = Request.Cookies["ztbscart"];
double Totle;
//Response.Write("|" + Request.Cookies["ztbscart"].Values.Keys[1].ToString() + "|");
//Response.End();
for (int i = 0; i < cookie.Values.Keys.Count; i++)
{
int id;
MyDr = MyDt.NewRow();
if (cookie.Values.AllKeys[i] != "" && cookie.Values[i] != "")
{
id = int.Parse(cookie.Values.AllKeys[i].ToString());
//ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product();
//ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product();
BookInfo _p = BookService.GetBookById(id.ToString());
// _p = p.GetModel(id);
MyDr[0] = id;
MyDr[1] = _p.Title;
MyDr[2] = cookie.Values[i];
MyDr[3] = _p.UnitPrice;
// MyDr[4] = _p.Discount;
// MyDr[5] = _p.Vipprice1;
// MyDr[3]=cookie.Value[i];
Totle = double.Parse(MyDr[2].ToString()) * double.Parse(MyDr[3].ToString());
MyDr[6] = Totle;
MyDt.Rows.Add(MyDr);
}
}
GridView1.DataSource = MyDt.DefaultView;
GridView1.DataBind();
}
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//编辑某行数量 yxy //sql8.net
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//取消更新 yxy //sql8.net
GridView1.EditIndex = -1;
BindGrid();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//更新数量 yxy //sql8.net
string num;
TextBox tempbx = new TextBox();
Label templb = new Label();
// tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6]).Controls[1];
tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6].FindControl("TextBox1"));
num = tempbx.Text.ToString();
HttpCookie cookie = new HttpCookie("ztbscart");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string id;
string tempnum;
id = GridView1.Rows[i].Cells[1].Text.ToString();
if (e.RowIndex == i)
tempnum = num;
else
{
//templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1];
templb = (Label)(GridView1.Rows[i].Cells[6]).FindControl("Label1");
tempnum = templb.Text.ToString();
}
if (tempnum.Trim() == "")
tempnum = "0";
//Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"<BR>");//测试用途 yxy//sql8.net
cookie.Values.Add(id, tempnum);
}
//Response.End();
TimeSpan ts = new TimeSpan(0, 0, 10, 0);
cookie.Expires = DateTime.Now + ts;
Response.AppendCookie(cookie);
GridView1.EditIndex = -1;
//Message.GoTo("AddToCart.aspx");
Response.Redirect("AddToCart.aspx");
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
//继续购物 yxy //sql8.net
//Message.WebClose();
Response.Redirect("Default.aspx");
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
//清空购物车 yxy //sql8.net
CheckBox tempcb = new CheckBox();
HttpCookie cookie = new HttpCookie("ztbscart");
Label templb = new Label();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1];
if (!tempcb.Checked)
{
string id;
string tempnum;
id = GridView1.Rows[i].Cells[1].Text.ToString();
// templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1];
templb = (Label)(GridView1.Rows[i].Cells[6]).FindControl("Label1");
tempnum = templb.Text.ToString();
if (tempnum.Trim() == "")
tempnum = "0";
//Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"<BR>");//测试用途 yxy//sql8.net
cookie.Values.Add(id, tempnum);
}
}
TimeSpan ts = new TimeSpan(0, 0, 10, 0);
cookie.Expires = DateTime.Now + ts;
Response.AppendCookie(cookie);
// Message.GoTo("AddToCart.aspx");
Response.Redirect("AddToCart.aspx");
}
protected void CheckAll_CheckedChanged(object sender, EventArgs e)
{
//全选事件 yxy //sql8.net
CheckBox tempcb = new CheckBox();
bool tempbl;
tempcb = (CheckBox)(GridView1.HeaderRow.Cells[0]).Controls[1];
tempbl = tempcb.Checked;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1];
tempcb.Checked = tempbl;
}
}
}
gaobaba2011 2010-09-07
  • 打赏
  • 举报
回复
我是用Session 做的
马老虎 2010-09-07
  • 打赏
  • 举报
回复
使用Cookie存储产品信息
然后就是对Cookie的读取和重新读取的工作了!
点击搜索
  • 打赏
  • 举报
回复
 using System;

  using System.Data;

  using System.Configuration;

  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;

  //文章来源:http://study.pctoday.net.cn/2_ASP.net.aspx

  public class CookieShoppingCart

  {

  /// <summary>

  /// 加入购物车

  /// </summary>

  /// <param name="ProductID"></param>

  /// <param name="Quantity"></param>

  public static void AddToShoppingCart(int ProductID, int Quantity, int Box)

  {

  if (HttpContext.Current.Request.Cookies["ShoppingCart"] == null)

  {

  HttpCookie oCookie = new HttpCookie("ShoppingCart");

  //Set Cookie to expire in 3 hours

  oCookie.Expires = DateTime.Now.AddYears(3);

  oCookie.Value = ProductID.ToString() + ":" + Quantity.ToString() + ":" + Box.ToString();

  HttpContext.Current.Response.Cookies.Add(oCookie);

  }

  //如果cookie已经存在

  else

  {

  bool bExists = false;

  HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];

  oCookie.Expires = DateTime.Now.AddYears(3);

  string ShoppingCartStr = oCookie.Value.ToString();

  string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });

  //查看cookie中是否有该产品

  string newCookie = "";

  for (int i = 0; i < arrCookie.Length; i++)

  {

  if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == ProductID.ToString().Trim())

  {

  bExists = true;

  string OldQuantity = arrCookie[i].Trim().Substring(arrCookie[i].Trim().IndexOf(':') + 1);//得到数量

  OldQuantity = OldQuantity.Remove(OldQuantity.LastIndexOf(":"));

  OldQuantity = (Convert.ToInt32(OldQuantity) + Quantity).ToString();

  arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + ":" + OldQuantity + ":" + Box.ToString();

  //HttpContext.Current.Response.Write(arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + "已存在!数量:" + OldQuantity + "<br>");

  //HttpContext.Current.Response.Write(arrCookie[i] + "<br>");

  }

  newCookie = newCookie + "," + arrCookie[i];

  }

  //如果没有该产品

  if (!bExists)

  {

  oCookie.Value = oCookie.Value + "," + ProductID.ToString() + ":" + Quantity.ToString() + ":" + Box.ToString();

  }
else

  {

  oCookie.Value = newCookie.Substring(1);

  }

  HttpContext.Current.Response.Cookies.Add(oCookie);

  HttpContext.Current.Response.Write("ShoppingCart:" + HttpContext.Current.Request.Cookies["ShoppingCart"].Value);

  }

  }

  /// <summary>

  /// 移除购物车子项

  /// </summary>

  /// <param name="ProductID"></param>

  public static void RemoveShoppingCart(int ProductID)

  {

  if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null)

  {

  HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];

  oCookie.Expires = DateTime.Now.AddYears(3);

  //Check if Cookie already contain same item

  string ShoppingCartStr = oCookie.Value.ToString();

  string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });

  string[] arrCookie2 = new string[arrCookie.Length - 1];

  int j = 0;

  string NewStr = "";

  for (int i = 0; i < arrCookie.Length; i++)

  {

  if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) != ProductID.ToString())

  NewStr = NewStr + "," + arrCookie[i];

  }

  if (NewStr == "")

  HttpContext.Current.Response.Cookies["ShoppingCart"].Value = "";

  else

  HttpContext.Current.Response.Cookies["ShoppingCart"].Value = NewStr.Substring(1);

  }

  }

  public static void UpdateShoppingCart(int ProductID, int Quantity, bool box)

  {

  int Box = 1;

  if (!box)

  Box = 0;

  if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null)

  {

  bool bExists = false;

  HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];

  oCookie.Expires = DateTime.Now.AddYears(3);

  string ShoppingCartStr = oCookie.Value.ToString();

  string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });

  //查看cookie中是否有该产品

  string newCookie = "";

  for (int i = 0; i < arrCookie.Length; i++)

  {

  if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == ProductID.ToString().Trim())

  arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + ":" + Quantity.ToString() + ":" + Box.ToString();

  newCookie = newCookie + "," + arrCookie[i];

  }

  HttpContext.Current.Response.Cookies["ShoppingCart"].Value = newCookie.Substring(1);

  }

  }

  public static DataTable GetShoppingCart()

  {

  DataTable dt = new DataTable();

  if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null && HttpContext.Current.Request.Cookies["ShoppingCart"].Value.Trim() != "")
{

  HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];

  oCookie.Expires = DateTime.Now.AddYears(3);

  string ShoppingCartStr = oCookie.Value.ToString();

  //HttpContext.Current.Response.Write(ShoppingCartStr);

  string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });

  //查看cookie中是否有该产品

  string newCookie = "";

  for (int i = 0; i < arrCookie.Length; i++)

  {

  newCookie = newCookie + "," + arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':'));

  }

  newCookie = newCookie.Substring(1);

  dt = Product.GetProductByProductIds(newCookie, -1);

  dt.Columns.Add("Quantity");

  dt.Columns.Add("Box");

  foreach (DataRow row in dt.Rows)

  {

  for (int i = 0; i < arrCookie.Length; i++)

  {

  if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == row["ProductId"].ToString())

  {

  row["Quantity"] = arrCookie[i].Substring(arrCookie[i].IndexOf(":") + 1);

  row["Quantity"] = row["Quantity"].ToString().Remove(row["Quantity"].ToString().IndexOf(":"));

  string Box = arrCookie[i].Substring(arrCookie[i].LastIndexOf(":") + 1);

  if (Box == "1")

  row["Box"] = true;

  else

  row["Box"] = false;

  }

  }

  }

  }

  else

  {

  dt = Database.GetDataTable("select top 0 * from View_ProductList");

  dt.Columns.Add("Quantity");

  }

  return dt;

  }

  }

  • 打赏
  • 举报
回复
zhanglongjason 2010-09-07
  • 打赏
  • 举报
回复
up我是用session做的

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧