protected void AddToCartButton_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
book_id = Convert.ToInt32(Request.QueryString["book_id"].ToString());
cmd.CommandText = "select * from Book where book_id = " + book_id + "";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
//book_id =Convert.ToInt32(dr["book_id"]);
title = dr["title"].ToString();
//quantity = dr["quantity"].ToString();
quantity = QuantityTxt.Text;
price = dr["price"].ToString();
}
//Restrict User to enter some quantity that he wants...
if(Convert.ToInt32(QuantityTxt.Text)>Convert.ToInt32(quantity))
{
ErrorMsglbl.Text = "Please Enter Lower Quantity";
}
else
{
ErrorMsglbl.Text = "";
}
// Creating Cookies to store the value and then i will assign to data table...
if (Request.Cookies["ShoppingCart"] == null)
{
Response.Cookies["ShoppingCart"].Value = book_id.ToString() + "," + title.ToString() + "," + quantity.ToString() + "," + price.ToString();
Response.Cookies["ShoppingCart"].Expires = DateTime.Now.AddDays(1);
}
else
{
Response.Cookies["ShoppingCart"].Value = Request.Cookies["ShoppingCart"].Value + "|" + book_id.ToString() + "," + title.ToString() + "," + quantity.ToString() + "," + price.ToString();
Response.Cookies["ShoppingCart"].Expires = DateTime.Now.AddDays(1);
}
Response.Redirect("BookDetails.aspx?book_id="+book_id.ToString()+"&Cat_ID="+ViewState["cat"]+"");
}// End Add To Cart Button...
答案 0 :(得分:2)
问题出在其他块
Response.Cookies["ShoppingCart"].Value = Request.Cookies["ShoppingCart"].Value +
"|" + book_id.ToString() + "," + title.ToString() +
"," + quantity.ToString() + "," + price.ToString();
您可以在此处将以前的Cookie值与新内容一起分配给新Cookie。对于例如如果你有" 1,Shoe,1,25"在你的cookie中再次将相同的产品添加到购物车中,你会得到类似" 1,Shoe,1,25 |的东西1,鞋子,1,25"。
这个问题可以通过多种方法解决
接近第一
String[] carts = Request.Cookies["ShoppingCart"].Value.Split("|")
bool bookIdExists = false;
foreach(string cartDetail in carts)
{
string bookId = cartDetail.Split(",")[0];
if(bookId == newBookId)
{
bookIdExists = true;
}
}
if(!bookIDExists)
{
//Add your new item to Cookie
}
第二种方法
public Class Cart
{
public int BookId {get; set;}
public string Title {get; set;}
public int Qty {get; set;}
public decimal Price {get; set}
}
List<Cart> carts =Session["Cart"]==null? new List<Cart>(): Session["Cart"] as List<Cart>;
var existingCart = carts.Where(x=> x.BookId==newBookId).FirstOrDefault();
if(existingCart==null)
{
Cart c= new Cart {
BookId = newBookId,
Title =newTitle,
Qty = newQty,
Price =newPrice
};
carts.Add(c);
Session["Cart"] = carts;
}
您可以采用更好的方法来解决问题。
但使用cookie来存储您的购物车详情是很糟糕的。