PUT – api/Carts/{id}

Now that we have added one cart record, let's move to update that record whenever a customer repeatedly hits the Add To Cart button. We already have the code that updates the quantity and price on the client-side table, so we just need to write the code to call the PUT endpoint to update the record, as follows:

function PutCart(cartItem) 
{
var cart =
{
Id: cartItem.attr('data-cart-id'),
Customerid: '910D4C2F-B394-4578-8D9C-7CA3FD3266E2',
Productid: cartItem.attr('data-product-id'),
Qty: cartItem.find('td.qty').html(),
Finalprice: cartItem.find('td.price').html().replace('$', '')
};
$.ajax({
url: 'http://localhost:57571/api/Carts/' + cart.Id,
type: "PUT",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(cart),
headers: { "Authorization": "Bearer eyJhbGciOiJSUzI1NiIs..." }
});
}

The important part of the preceding code is the URL, which also contains the cart Id because the route is actually api/Carts/{id}. The data goes inside the body.

The parameter cartItem is the row which can be passed from the AddToCart function as follows:

// Update Cart in Database: PUT /api/Carts/{id}
PutCart($('#tblCart').find('tr[data-product-id=' + productId + ']'));

The API action should look as follows:

// PUT: api/Carts/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCart([FromRoute] Guid id, [FromBody] Cart cart)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != cart.Id)
{
return BadRequest();
}
_context.Entry(cart).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CartExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}

Notice that id is read from the route, as it is marked with the attribute [FromRoute], and the cart object is read from the body of the request, as it is marked [FromBody]. If an ID is not sent with a route, the client would receive a 400 BadRequest error.

The API action has now updated the record with the necessary details, as shown in the following screenshot:

As you can see, we have clicked Add To Cart four times. The finalPrice is calculated accordingly as 49.99 * 4.