採用 Session 儲存購物車資料,搭配 Hashtable 以商品 ID 為 Key、數量為 Value,實作輕量級購物車功能。適用於中小型電商專案。
int)// Session["Cart"] 存放 Hashtable
// Key: productId (int), Value: quantity (int)
Hashtable cart = Session["Cart"] as Hashtable ?? new Hashtable();
id:商品 ID(0 表示檢視購物車)opt:操作類型(0=檢視, 1=新增, 2=增加數量, 3=減少數量, 4=刪除)public void AddItem(int productId) {
Hashtable cart = GetCart();
if (cart.ContainsKey(productId)) {
cart[productId] = (int)cart[productId] + 1;
} else {
cart[productId] = 1;
}
SaveCart(cart);
}
public void IncreaseQty(int productId) {
Hashtable cart = GetCart();
if (cart.ContainsKey(productId)) {
cart[productId] = (int)cart[productId] + 1;
SaveCart(cart);
}
}
public void DecreaseQty(int productId) {
Hashtable cart = GetCart();
if (cart.ContainsKey(productId)) {
int qty = (int)cart[productId] - 1;
if (qty <= 0) {
cart.Remove(productId); // 數量歸零移除該商品
} else {
cart[productId] = qty;
}
SaveCart(cart);
}
}
public void RemoveItem(int productId) {
Hashtable cart = GetCart();
if (cart.ContainsKey(productId)) {
cart.Remove(productId);
SaveCart(cart);
}
}
public void BindCartGrid() {
Hashtable cart = GetCart();
var dt = new DataTable();
dt.Columns.Add("ProductID", typeof(int));
dt.Columns.Add("ProductName", typeof(string));
dt.Columns.Add("UnitPrice", typeof(decimal));
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("SubTotal", typeof(decimal));
foreach (DictionaryEntry entry in cart) {
int pid = (int)entry.Key;
int qty = (int)entry.Value;
// 從資料庫查詢商品明細
Product p = ProductDAO.GetById(pid);
if (p != null) {
dt.Rows.Add(pid, p.Name, p.Price, qty, p.Price * qty);
}
}
gvCart.DataSource = dt;
gvCart.DataBind();
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
int id = Request.QueryString["id"].ToInt(0);
int opt = Request.QueryString["opt"].ToInt(0);
switch (opt) {
case 1: AddItem(id); break;
case 2: IncreaseQty(id); break;
case 3: DecreaseQty(id); break;
case 4: RemoveItem(id); break;
}
BindCartGrid();
}
}
Dictionary<int, int>,型別安全且效能更佳所有操作需驗證 productId 合法性,防止惡意竄改參數操作他人購物車。生產環境建議加入 CSRF Token 驗證。