Reputation: 388
I am trying to have this AJAX code working. When I run the WebStore it display a list of categories which If I clicked on 1 category, I can then select a product. The product show up and I can added to the cart. After it's been added to the cart, I clicked on Remove from the Cart and nothing is refreshing. I based my solution on the MVC Music Store and I also read the old solution was not updated for this Ajax Part. I found this instead and I guess I am missing something. I noticed an URL change localhost:49523/Panier#. Any idea why a # is there ?
Thanks
index.cshtml from panier
@model Tp1WebStore3.ViewModels.ShoppingCartViewModel
@{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function handleUpdate(context) {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
$('#row-' + data.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + data.CartCount + ')');
$('#update-message').text(data.Message);
$('#cart-total').text(data.CartTotal);
}
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
@Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
@foreach (var item in Model.CartItems)
{
<tr id="[email protected]">
<td>
@Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
@item.Produit.Prix
</td>
<td id="[email protected]">
@item.Quantite
</td>
<td>
<a href="#" class="RemoveLink" data-id="@item.ProduitId"> Remove from Cart </a>
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
@Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
Modify Index.cshtml
@model Tp1WebStore3.ViewModels.ShoppingCartViewModel
@{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
I am adding also the ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
I got more information. When I ran Chrome with PF12 and Network, I saw a page not found
In my Panier I got this key (newly created) for the CartId : dbfac4de-ae5e-4fbf-a44a-f6bb8ee3f2fc
In Chrome it complaining about this: RemoveFromCart?id=dbfac4de-ae5e-4fbf-a44a-f6bb8ee3f2fc&_=1394045298037 /Panier
I don't understand the next part of the key (concatenation) &_=1394045298037 My ProduitId are define like this for the key: 3
Can anyone explain this to me ?
Upvotes: 0
Views: 1579
Reputation: 1039498
You have a remove anchor:
<a href="#" class="RemoveLink" data-id="@item.ProduitId">Remove from Cart </a>
and some javascript handleUpdate
function which is absolutely never called:
<script type="text/javascript">
function handleUpdate(context) {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
$('#row-' + data.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + data.CartCount + ')');
$('#update-message').text(data.Message);
$('#cart-total').text(data.CartTotal);
}
</script>
You also seem to be using an extremely outdated version of jquery:
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
and a dinosaurly old, stone age outdated and deprecated Microsoft AJAX scripts:
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
So start by removing the dinosaurly old scripts from your ASP.NET MVC application as well as the handleUpdate
function which is absolutely never used.
Then you could write some jQuery ajax function that will subscribe to the click event of your anchor and perform an AJAX request:
<script type="text/javascript">
$(function() {
$('.RemoveLink').click(function() {
$.ajax({
url: '/ShoppingCart/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function(result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
Also you should learn how to debug your AJAX calls in your web browser. All modern web browsers (such as Google Chrome) come with javascript debugging tools that would help you debug and analyze such problems. So don't hesitate to fire your debugging toolbar using F12 and look at the Network
tab. It will provide you useful information about all network requests (including AJAX) that the browser is making. The Console
tab will show you any potential javascript errors you might be having in your code. So instead of saying on StackOverflow that nothing happens when you click on some anchor, next time use your javascript debugging toolbar to analyze what happens under the covers.
Upvotes: 1