in PartsUnlimited-aspnet45/src/PartsUnlimitedWebsite/Controllers/ShoppingCartController.cs [101:150]
public async Task<ActionResult> RemoveFromCart([FromUri] int id)
{
// Start timer for save process telemetry
var startTime = DateTime.Now;
// Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(db, HttpContext);
// Get the name of the product to display confirmation
var cartItem = db.CartItems.Include("Product").Single(item => item.CartItemId == id);
string productName = cartItem.Product.Title;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
await db.SaveChangesAsync(CancellationToken.None);
string removed = (itemCount > 0) ? " 1 copy of " : string.Empty;
// Trace remove process
var measurements = new Dictionary<string, double>()
{
{"ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
};
telemetry.TrackEvent("Cart/Server/Remove", null, measurements);
// Display the confirmation message
var items = cart.GetCartItems();
var itemsCount = items.Sum(x => x.Count);
var subTotal = items.Sum(x => x.Count * x.Product.Price);
var shipping = itemsCount * (decimal)5.00;
var tax = (subTotal + shipping) * (decimal)0.05;
var total = subTotal + shipping + tax;
var results = new ShoppingCartRemoveViewModel
{
Message = removed + productName +
" has been removed from your shopping cart.",
CartSubTotal = subTotal.ToString("C"),
CartShipping = shipping.ToString("C"),
CartTax = tax.ToString("C"),
CartTotal = total.ToString("C"),
CartCount = itemsCount,
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
}