首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET Session + Hashtable 實作購物車完整範例

     編輯:關於ASP.NET

採用 Session 儲存購物車資料,搭配 Hashtable 以商品 ID 為 Key、數量為 Value,實作輕量級購物車功能。適用於中小型電商專案。

為何選擇 Hashtable

  • Key/Value 結構天然符合「商品 ID → 數量」對應
  • 查找、新增、刪除皆為 O(1) 平均複雜度
  • 支援任意型別 Key/Value(此處均為 int)

核心資料結構

// Session["Cart"] 存放 Hashtable
// Key: productId (int), Value: quantity (int)
Hashtable cart = Session["Cart"] as Hashtable ?? new Hashtable();

購物車頁面 Vehicle.aspx 參數設計

  • id:商品 ID(0 表示檢視購物車)
  • opt:操作類型(0=檢視, 1=新增, 2=增加數量, 3=減少數量, 4=刪除)

關鍵操作邏輯

新增商品 (opt=1)

public void AddItem(int productId) {
    Hashtable cart = GetCart();
    if (cart.ContainsKey(productId)) {
        cart[productId] = (int)cart[productId] + 1;
    } else {
        cart[productId] = 1;
    }
    SaveCart(cart);
}

增加數量 (opt=2)

public void IncreaseQty(int productId) {
    Hashtable cart = GetCart();
    if (cart.ContainsKey(productId)) {
        cart[productId] = (int)cart[productId] + 1;
        SaveCart(cart);
    }
}

減少數量 (opt=3)

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);
    }
}

刪除商品 (opt=4)

public void RemoveItem(int productId) {
    Hashtable cart = GetCart();
    if (cart.ContainsKey(productId)) {
        cart.Remove(productId);
        SaveCart(cart);
    }
}

顯示購物車內容(繫結 GridView)

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();
}

完整 Page_Load 流程

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();
    }
}

擴充建議

  • 序列化儲存:將 Hashtable 序列化存入資料庫,支援跨裝置/跨 Session 持久化
  • 庫存檢查:新增/增加數量時即時查詢庫存,防止超賣
  • 優惠計算:結帳前套用優惠券、滿額折扣等促銷規則
  • 轉型 Dictionary:.NET 2.0+ 建議改用 Dictionary<int, int>,型別安全且效能更佳

安全性注意

所有操作需驗證 productId 合法性,防止惡意竄改參數操作他人購物車。生產環境建議加入 CSRF Token 驗證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved