You need to add the Action to delete the item from the cart. This will be called when the button is clicked.
[HttpGet]publicIActionResultRemoveFromCart(CartDto cart){try {_commerceApi.Uow.Execute(uow => {var store =CurrentPage?.Value<StoreReadOnly>("store", fallback:Fallback.ToAncestors);if (store ==null) return;var order =_commerceApi.GetOrCreateCurrentOrder(store.Id) .AsWritable(uow) .RemoveOrderLine(cart.OrderLineId);_commerceApi.SaveOrder(order);uow.Complete(); }); }catch (ValidationException) {ModelState.AddModelError(string.Empty,"Failed to remove product from cart");returnCurrentUmbracoPage(); }TempData["SuccessMessage"] ="Item removed";returnRedirectToCurrentUmbracoPage();}
A try-catch block captures any validation errors that may occur when updating items in the cart.
The store variable is used to access the store to retrieve the store ID.
order is used to retrieve the current order. In the Commerce API, everything is read-only for performance so you need to make it writable to add the product.
SaveOrder is called to save the order.
If there are any validation errors, they are added to a ModelState error, and the user is redirected back to the current page.
TempData stores a message to be displayed to the user if the product has been successfully updated.
Umbraco Commerce uses the Unit of Work pattern to complete saving the item (uow.Complete). When retrieving or saving data ideally you would want the entire transaction to be committed. However, if there is an error nothing is changed on the database.
If you have followed the Add item to cart article, run the application, add an item to your cart, and navigate to your cart.cshtml page. Clicking the Remove Item button will delete the item in your cart and display a message.