in Hands-on lab/lab-files/src/src/PartsUnlimitedWebsite/Controllers/ShoppingCartController.cs [103:144]
public async Task<IActionResult> RemoveFromCart(Request request)
{
// Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(_db, HttpContext);
// Get the name of the album to display confirmation
var cartItem = await _db.CartItems
.Where(item => item.CartItemId == request.Id)
.Include(c => c.Product)
.SingleOrDefaultAsync();
string message;
int itemCount;
if (cartItem != null)
{
// Remove from cart
itemCount = cart.RemoveFromCart(request.Id);
await _db.SaveChangesAsync(request.CancellationToken);
string removed = (itemCount > 0) ? " 1 copy of " : string.Empty;
message = removed + cartItem.Product.Title + " has been removed from your shopping cart.";
}
else
{
itemCount = 0;
message = "Could not find this item, nothing has been removed from your shopping cart.";
}
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = message,
CartTotal = cart.GetTotal().ToString(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = request.Id
};
return Json(results);
}