|
| 1 | +## Delete item from cart |
| 2 | +Following on from the previous guide on [updating an item in the cart](/umbraco-commerce/how-to-guides/update-cart.md), we will now look at how to delete an item from the cart. |
| 3 | + |
| 4 | +{% hint style="warning" %} |
| 5 | +This tutorial focuses only on the delete functionality. Please see the other guides for more information for areas not covered here. |
| 6 | +{% endhint %} |
| 7 | + |
| 8 | +Your view will be similar to the below for the `cart.cshtml` page. |
| 9 | + |
| 10 | +```csharp |
| 11 | +@inherits UmbracoViewPage |
| 12 | +@{ |
| 13 | + var store = Model.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors); |
| 14 | + var currentOrder = CommerceApi.Instance.GetCurrentOrder(store!.Id); |
| 15 | + if (currentOrder == null) return; |
| 16 | + |
| 17 | + @using (Html.BeginUmbracoForm("UpdateCart", "CartSurface")) |
| 18 | + { |
| 19 | + @foreach (var item in currentOrder.OrderLines.Select((ol, i) => new |
| 20 | + { |
| 21 | + OrderLine = ol, |
| 22 | + Index = i |
| 23 | + })) |
| 24 | + { |
| 25 | + <p> |
| 26 | + @Html.Hidden($"orderLines[{item.Index}].Id", item.OrderLine.Id) |
| 27 | + @item.OrderLine.Name @Html.Hidden($"orderLines[{item.Index}].Quantity", (int)item.OrderLine.Quantity, new { @type = "number" }) |
| 28 | + @Html.Hidden($"orderLines[{item.Index}].ProductReference", item.OrderLine.ProductReference) |
| 29 | + <a href="@Url.SurfaceAction("RemoveFromCart", "CartSurface", new { OrderLineId = item.OrderLine.Id })">Remove Item</a> |
| 30 | + </p> |
| 31 | + |
| 32 | + } |
| 33 | + |
| 34 | + <button type="submit">Update Cart</button> |
| 35 | + |
| 36 | + var success = TempData["SuccessMessage"]?.ToString(); |
| 37 | + |
| 38 | + if (!string.IsNullOrWhiteSpace(success)) |
| 39 | + { |
| 40 | + <div class="success">@success</div> |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +- The below code allows the Umbraco `SurfaceAction` to call `RemoveFromCart` when the link is clicked as well as passing the `OrderLineId`. |
| 47 | +```csharp |
| 48 | +<a href="@Url.SurfaceAction("RemoveFromCart", "BasketSurface", new { OrderLineId = item.OrderLine.Id })">Remove</a> |
| 49 | +``` |
| 50 | +## Adding the Controller |
| 51 | + |
| 52 | +Create a new Controller called `CartSurfaceController.cs` |
| 53 | + |
| 54 | +{% hint style="warning" %} |
| 55 | + |
| 56 | +The namespaces used in this Controller are important and need to be included. |
| 57 | + |
| 58 | + using Microsoft.AspNetCore.Mvc; |
| 59 | + using Umbraco.Cms.Core.Cache; |
| 60 | + using Umbraco.Cms.Core.Logging; |
| 61 | + using Umbraco.Cms.Core.Models.PublishedContent; |
| 62 | + using Umbraco.Cms.Core.Routing; |
| 63 | + using Umbraco.Cms.Core.Services; |
| 64 | + using Umbraco.Cms.Core.Web; |
| 65 | + using Umbraco.Cms.Infrastructure.Persistence; |
| 66 | + using Umbraco.Cms.Web.Website.Controllers; |
| 67 | + using Umbraco.Commerce.Common.Validation; |
| 68 | + using Umbraco.Commerce.Core.Api; |
| 69 | + using Umbraco.Commerce.Core.Models; |
| 70 | + using Umbraco.Commerce.Extensions; |
| 71 | + using Umbraco.Extensions; |
| 72 | + |
| 73 | +{% endhint %} |
| 74 | + |
| 75 | +```csharp |
| 76 | +public class CartSurfaceController : SurfaceController |
| 77 | +{ |
| 78 | + public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) |
| 79 | + { |
| 80 | + _commerceApi = commerceApi; |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
| 84 | + |
| 85 | +The equivalent code for having this as a Primary Constructor |
| 86 | + |
| 87 | +```csharp |
| 88 | +public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) |
| 89 | +{ |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | + |
| 94 | + |
| 95 | +The `CartDto` is a class that is used to pass data to the Controller. In this instance it is passing over the OrderLineId. |
| 96 | + |
| 97 | +```csharp |
| 98 | + public class CartDto |
| 99 | + { |
| 100 | + public Guid OrderLineId { get; set; } |
| 101 | + } |
| 102 | +``` |
| 103 | + |
| 104 | +We now need to add the `Action` in order to delete the item from the cart. This will be called when the button is clicked. |
| 105 | + |
| 106 | +```csharp |
| 107 | + [HttpGet] |
| 108 | + public IActionResult RemoveFromCart(CartDto cart) |
| 109 | + { |
| 110 | + try |
| 111 | + { |
| 112 | + _commerceApi.Uow.Execute(uow => |
| 113 | + { |
| 114 | + var store = CurrentPage?.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors); |
| 115 | + |
| 116 | + if (store == null) return; |
| 117 | + |
| 118 | + var order = _commerceApi.GetOrCreateCurrentOrder(store.Id) |
| 119 | + .AsWritable(uow) |
| 120 | + .RemoveOrderLine(cart.OrderLineId); |
| 121 | + |
| 122 | + _commerceApi.SaveOrder(order); |
| 123 | + |
| 124 | + uow.Complete(); |
| 125 | + }); |
| 126 | + } |
| 127 | + catch (ValidationException) |
| 128 | + { |
| 129 | + ModelState.AddModelError(string.Empty, "Failed to remove product from cart"); |
| 130 | + |
| 131 | + return CurrentUmbracoPage(); |
| 132 | + } |
| 133 | + |
| 134 | + TempData["SuccessMessage"] = "Item removed"; |
| 135 | + |
| 136 | + return RedirectToCurrentUmbracoPage(); |
| 137 | + } |
| 138 | +``` |
| 139 | + |
| 140 | +- A `try catch` block is used to capture any validation errors that may occur when updating items in the cart. |
| 141 | +- `store` variable is used to access the store to retrieve the store ID. |
| 142 | +- `order` is used to retrieve the current order. In the Commerce Api everything is read-only for performance so we need to make it writable in order to add the product. |
| 143 | +- `SaveOrder` is called to save the order. |
| 144 | +- If there are any validation errors, they are added to ModelState error and the user is redirected back to the current page. |
| 145 | +- `TempData` is used to store a message to be displayed to the user if the product has been succesfully updated. |
| 146 | + |
| 147 | +{% hint style="warning" %} |
| 148 | +Umbraco Commerce uses the Unit of Work pattern in order 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 then nothing is changed on the database. |
| 149 | +{% endhint %} |
| 150 | + |
| 151 | +If you have followed the 'Add item to cart' article then run the application, add an item to your cart and navigate to your cart.cshtml page. Clicking the `Remove Item` button would delete the the item in your cart and display a success message. |
0 commit comments