public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; } //商品ID
public int Amount { get; set; } //數量
public int SubTotal { get; set; } //小計
public class CartItem : OrderItem
public Product Product { get; set; } //商品內容
public string imageSrc { get; set; } //商品圖片
購物車控制器
在
Controller資料夾
建立空控制器
CartController.cs
接著需要完成以下購物車的三個主要功能:
AddtoCart() : 加入購物車
RemoveItem() : 移除購物車項目
Index() : 顯示購物車頁面
AddtoCart 加入購物車
點擊加入購物車後會執行的Action
public IActionResult AddtoCart(int id)
//取得商品資料
CartItem item = new CartItem
Product = _context.Product.Single(x => x.Id.Equals(id)),
Amount = 1,
SubTotal = _context.Product.Single(m => m.Id == id).Price
//判斷 Session 內有無購物車
if (SessionHelper.
GetObjectFromJson<List<CartItem>>(HttpContext.Session, "cart") == null)
//如果沒有已存在購物車: 建立新的購物車
List<CartItem> cart = new List<CartItem>();
cart.Add(item);
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
//如果已存在購物車: 檢查有無相同的商品,有的話只調整數量
List<CartItem> cart = SessionHelper.
GetObjectFromJson<List<CartItem>>(HttpContext.Session, "cart");
int index = cart.FindIndex(m => m.Product.Id.Equals(id));
if (index != -1)
cart[index].Amount += item.Amount;
cart[index].SubTotal += item.SubTotal;
cart.Add(item);
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
return NoContent(); // HttpStatus 204: 請求成功但不更新畫面
RemoveItem 移除購物車項目
public IActionResult RemoveItem(int id)
//向 Session 取得商品列表
List<CartItem> cart = SessionHelper.
GetObjectFromJson<List<CartItem>>(HttpContext.Session, "cart");
//用FindIndex查詢目標在List裡的位置
int index = cart.FindIndex(m => m.Product.Id.Equals(id));
cart.RemoveAt(index);
if(cart.Count < 1)
SessionHelper.Remove(HttpContext.Session, "cart");
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
return RedirectToAction("Index");
Index 購物車頁面
public IActionResult Index()
//向 Session 取得商品列表
List<CartItem> CartItems = SessionHelper.
GetObjectFromJson<List<CartItem>>(HttpContext.Session, "cart");
//計算商品總額
if(CartItems != null)
ViewBag.Total = CartItems.Sum(m => m.SubTotal);
ViewBag.Total = 0;
return View(CartItems);
最後建立前端畫面View/Cart/Index.cshtml
,隨意顯示商品的欄位,我們的購物車就大功告成了!