fagol fagol - 1 year ago 61
Ajax Question

How to update old model with new model with Ajax?

So far, I can list and delete a product from the cart. Upon delete, I remove the selected product and update the cart with Ajax:

$.post("/Cart/RemoveFromCart", { "id": $(this).data('id' }

But, I need to update the page with ajax without postback.

Clarify: The
in Ajax contains the new updated cart. I just need to update the page as well somehow.

$(document).ready(function () {
$('.remove-from-cart').click(function () {

$.post("/Cart/RemoveFromCart", { "id": $(this).data('id' },
function (data) {

// Update the page with new models(data)


This is my ajax-function in Controllers:

public List<Products> RemoveFromCart(Guid id) {

//remove and update the cart/models

return newCartModel;

In View:

@foreach (var item in Model) {

//....some other property

<button class="remove-to-cart" data-id="@item.Id">Remove from cart</button>

Answer Source

There is no need to return all the cart items back to the view again. All you need to do is remove the item associated with button you clicked from the current page.

Modify the RemoveFromCart() method to just return a value indicating if the item was successfully removed or not

public JsonResult RemoveFromCart(Guid id)
    // remove and update the cart/models
    return Json(true); // to indicate sucess
    // or return Json(null); to indicate something failed

Then in the ajax success callback, if successful, remove the associated elements from the DOM. To make selection easier, give the containing element a class name

@foreach (var item in Model)
    <div class="item"> // add class name
        <button class="remove-to-cart" data-id="@item.Id">Remove from cart</button>

$('.remove-from-cart').click(function () {
    var container = $(this).closest('.item'); // get the 'container'       
    $.post("/Cart/RemoveFromCart", { "id": $(this).data('id' }, function (data) {
        if (data) {
            container.remove(); // remove from the DOM
        } else {
            // Oops something went wrong - display ad error message?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download