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