fagol fagol - 4 days ago 5
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
data
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) {
<div>
<label>
@item.Name
</label>

//....some other property

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

Answer

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

[HttpPost]
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
        <label>@item.Name</label>
        ....
        <button class="remove-to-cart" data-id="@item.Id">Remove from cart</button>
    </div>
}

$('.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?
        }
    });                
});
Comments