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

ASP.NET 利用 Session + Hashtable 實現購物車

     編輯:關於ASP.NET

經典輕量級購物車實現:`Hashtable` 存儲 `商品ID → 數量`,存放於 `Session`,無需資料庫即可支援加入、修改、顯示、結帳流程。

加入購物車

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "Buy") return;
    string pid = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].ToString();

    Hashtable cart = Session["Cart"] as Hashtable ?? new Hashtable();
    cart[pid] = cart.ContainsKey(pid) ? (int)cart[pid] + 1 : 1;
    Session["Cart"] = cart;
}

顯示購物車

// 綁定到 DataList/Repeater/GridView
DataList1.DataSource = Session["Cart"] as Hashtable;
DataList1.DataBind();

前端模板:

<ItemTemplate>
    <%# ((DictionaryEntry)Container.DataItem).Key %> 
    <asp:TextBox ID="txtQty" Text='<%# ((DictionaryEntry)Container.DataItem).Value %>' />
    <asp:Label ID="lblKey" Text='<%# ((DictionaryEntry)Container.DataItem).Key %>' Visible="false" />
</ItemTemplate>

更新數量

protected void btnUpdate_Click(object sender, EventArgs e)
{
    Hashtable cart = Session["Cart"] as Hashtable;
    if (cart == null) return;

    foreach (DataListItem item in DataList1.Items)
    {
        string pid = ((Label)item.FindControl("lblKey")).Text;
        int newQty = int.Parse(((TextBox)item.FindControl("txtQty")).Text);
        if (newQty > 0) cart[pid] = newQty;
        else cart.Remove(pid); // 數量歸零移除
    }
    Session["Cart"] = cart;
    DataList1.DataBind();
}

結帳轉單

protected void btnCheckout_Click(object sender, EventArgs e)
{
    Hashtable cart = Session["Cart"] as Hashtable;
    if (cart == null || cart.Count == 0) return;

    foreach (DictionaryEntry de in cart)
    {
        string pid = de.Key.ToString();
        int qty = (int)de.Value;
        // 寫入訂單明細表 ...
    }
    Session.Remove("Cart"); // 清空購物車
    Response.Redirect("OrderSuccess.aspx");
}

優缺點與擴充

優點缺點/擴充方向
代碼極簡、無資料庫鎖爭用、Session 自動過期清理重啟失效 → 改用資料庫/Redis 持久化
適合中小流量、單機部署無庫存檢查 → 加入庫存服務驗證
前後端分離易於遷移無優惠券/促銷邏輯 → 擴充 Value 為複雜物件

生產建議:`Hashtable` → `Dictionary`,`CartItem` 包含數量、單價、屬性、促銷資訊,並引入分散式 Session/Redis。

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