已經做到爛掉的 CRUD 又來了,最後還是要把訂單管理的頁面建出來
沿用前面建立的 OrderController.cs
控制器
這次需要建立兩個 Action:
public async Task<IActionResult> Index()
{
List<OrderViewModel> orderVM = new List<OrderViewModel>();
var userId = _userManager.GetUserId(User);
var orders = await _context.Order.
OrderByDescending(k => k.OrderDate). //依照日期排序
Where(m => m.UserId == userId).ToListAsync();
foreach(var item in orders)
{
item.OrderItem = await _context.OrderItem.
Where(p => p.OrderId == item.Id).ToListAsync();
var vm = new OrderViewModel()
{
Order = item,
CartItems = GetOrderItems(item.Id)
};
orderVM.Add(vm);
}
return View(orderVM);
}
private List<CartItem> GetOrderItems(int orderId)
{
var OrderItems = _context.OrderItem.Where(p => p.OrderId == orderId).ToList();
List<CartItem> orderItems = new List<CartItem>();
foreach (var orderitem in OrderItems)
{
CartItem item = new CartItem(orderitem);
item.Product = _context.Product.Single(x => x.Id == orderitem.ProductId);
orderItems.Add(item);
}
return orderItems;
}
可以比照前面在結帳流程顯示訂單的方式
public async Task<IActionResult> Details(int? Id)
{
if (Id == null)
{
return NotFound();
}
var order = await _context.Order.FirstOrDefaultAsync(m => m.Id == Id);
if (order.UserId != _userManager.GetUserId(User))
{
return NotFound();
}
else
{
order.OrderItem = await _context.OrderItem.
Where(p => p.OrderId == Id).ToListAsync();
ViewBag.orderItems = GetOrderItems(order.Id);
}
return View(order);
}
在 _Layout.cshtml
引用 SignInManager
來得知登入狀態
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
加入選項,並設定只有在登入狀態下才看的到 [我的訂單] 選項
@if (SignInManager.IsSignedIn(User)){
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Order" asp-action="Index">我的訂單</a>
</li>
}
到這裡前台該有的功能都完成了,鐵人賽也到尾聲了,剩下的天數就來慢慢收尾吧!