I work on a webpage which has a shopping basket. My problem is that the shopping basket doesn't show the number of elements when I add a new item. It shows only after I reload the page manually. But I need to show the number of items right after I add a new item.
This is the button which add the new item to basket:
<button type="button" class="btn btn-success" onclick="addtoBasket(this)" id="addToBasket" data-id=@c.ID>Add</button>
This is the ajax call:
<script>
function addtoBasket(obj) {
var $button = $(obj);
var testId = $button.data("id"); //reading the data-id of clicked button
var UrlSettings = {
url: '@Url.Action("SetShoppingCartElement", "Purchase")'
}
$.ajax({
url: UrlSettings.url,
data: { 'id': testId },
type: "post",
cache: false,
success: function (data) {
location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
and this is my ActionResult in controller:
public ActionResult SetShoppingCartElement(string id)
{
int productId = int.TryParse(id, out productId) ? productId : 0;
Product product = productRepository.GetProductByID(productId);
List<Product> list = HttpContext.Session["ShoppingCart"] as List<Product>;
if (list == null)
list = new List<Product>();
bool alreadyExists = list.Any(x => x.Id == product.Id);
if (!alreadyExists)
{
list.Add(product);
Session["ShoppingCart"] = list;
Session["ShoppingCartCount"] = list.Count;
}
return View();
}
The Session["ShoppingCartCount"] is set correctly, but it is not showing the result only after a page refresh. The Session["ShoppingCartCount"] is displayed on a Layout view. The location.reload() doesn't fix my problem. Can you advise how to resolve this problem? Thanks!