简体   繁体   中英

Refresh partial view using jquery

This partial view is used to list cart-items:

<ul class="cart-dropdown">
    <li>
        <div class="cart-items cart-caption">
            <ul>
                @foreach (var i in Model.CartItems)
                {
                    <li id="list-item-@i.item.ItemID">
                        <div class="container-fluid item-wrap" style="position: relative">
                            <div class="item-remove">
                                <a href="#" class="RemoveLink"
                                   data-id="@i.RecordID" data-itemid="@i.item.ItemID">
                                    x
                                </a>
                            </div>
                            <div class="col-md-2 item-img">
                                <div class="row-cart">
                                    <img alt="" id="cartImg" height="71" width="75" src="@i.item.ImageUrl">
                                </div>
                            </div>
                            <div class="col-md-5 item-info">
                                <div class="row-cart">
                                    <div class="brand-name">
                                        <a href="#" class="brandName">
                                            @i.item.BrandName
                                        </a>
                                    </div>
                                    <div class="product-name">
                                        <a href="#" class="productName">
                                            @i.item.ItemName
                                        </a>
                                    </div>
                                    <div class="product-qty">
                                        <p class="productQTY" id="item-count-@i.item.ItemID">
                                            @i.Count x @i.item.ItemPrice
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-5 price-info">
                                <div class="row-cart" style="margin-top: 10px">
                                    <div class="col-md-6">
                                        <div class="row-mrp">
                                            <span class="cartItemPrice" id="item-total-@i.item.ItemID">
                                                Rs @(@i.Count * @i.item.ItemPrice)
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                }
            </ul>
        </div>
    </li>
    <li class="clearfix">
        <div class="col-md-6">
            <div class="row-cart sub-cost" style="background: #fff; margin-left: -10px; margin-right: 0">
                <p>
                    Sub Total :
                    <span style="float: right">
                        Rs
                        <span class="ng-binding"></span>
                    </span>
                </p>
                <p>
                    Delivery Charge :
                    <span qa="delChargeMB" style="float: right">Free</span>
                </p>
            </div>
            <div class="row-cart cart-chkout-btn">
                <button type="button">View Basket &amp; Checkout</button>
            </div>
        </div>
    </li>
</ul>    

Above partial view is rendered when user clicks on "My cart" button. I need to allow customers to remove any cart-item they like by clicking a 'remove' button inside _cartDetails.cshtml. This jQuery code is being used to accomplish this task:

$(function () {
    $(".RemoveLink").click(function () {
        var recordToDelete = $(this).attr("data-id");
        var itemID = $(this).attr("data-itemid");
        if (recordToDelete != '') {
            $.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete, "itemID": itemID },
                function (data) {
                    if (data.ItemCount == 0) {
                        $('#list-item-' + recordToDelete).fadeOut('slow');
                    }
                    else {
                        $('#item-count-' + recordToDelete).text(data.ItemCount + " x " + data.ItemPrice);
                        $('#item-total-' + recordToDelete).text(data.ItemCount * data.ItemPrice);
                    }
                    $('#update-message').text(data.Message);
                    $(".confirmItemCart").show();
                    $(".confirmItemCart").addClass("collapsed");
                    $('.confirmItemCart').delay(30000).fadeOut('slow');
                    $('#cart-status').text('Cart (' + data.CartCount + ')');
                    $('#cart-total').text(data.CartTotal);
                });
        }
    })
});

(UPDATED) 更新)

    public ActionResult cartDropDown()
        {
              return RedirectToAction("cartDropDownChild");
        }

    [ChildActionOnly]
    public ActionResult cartDropDownChild()
    {
        var cart = ShoppingCart.GetCart(this.HttpContext);
        // Set up list of cart items with total value
        var viewModel = new ShoppingCartViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal(),
            ItemCount = cart.GetCount(),
            Message = Server.HtmlEncode("There are no items in your cart. Continue shopping.")
        };
        foreach (var item in viewModel.CartItems)
        {
            item.item = db.Items.Single(i => i.ItemID == item.ItemID);
        }
        return PartialView("_cartDetails", viewModel);
    }    

This code is successfully removing items from the cart-items list but not updating the partial view (_cartDetails.cshtml). In debug mode, I've checked the values for the ( data ) which is returned from the ajax call and all values are correct. It is just the binding of those values with the _cartDetails html elements that is not working. Maybe I'm missing out something. Someone please guide.

Thanks in advance.

This is actually a system design related issues. Partial view gets rendered when the page loads.

When you are removing an item why don't you post to a child action which would render the same partial view and return the html. Then you can put the html in place. You do not need to handle the list-item, cart-total, cart-status etc. manually.

Add the [ChildActionOnly] filter to the action that renders the cart information section.

Then in the action: return PartialView("_cartDetails");

For example:

Move the logic from cartDropDown() function to a private function which will return a viewModel object. Then call that private function from both cartDropDown() and also in RemoveFromCart action (after deleting the data).

[ChildActionOnly]
public ActionResult cartDropDown()
{
    return PartialView("_cartDetails", preparecartDropDown(this.HttpContext));
}

[ChildActionOnly]
public ActionResult RemoveFromCart(...)
{
    //Delete data
    return PartialView("_cartDetails", preparecartDropDown(this.HttpContext));
}

private ShoppingCartViewModel preparecartDropDown(HttpContext context)
{
    var cart = ShoppingCart.GetCart(context);
    var viewModel = new ShoppingCartViewModel
    {
        CartItems = cart.GetCartItems(),
        CartTotal = cart.GetTotal(),
        ItemCount = cart.GetCount(),
        Message = Server.HtmlEncode("There are no items in your cart. Continue shopping.")
    };
    foreach (var item in viewModel.CartItems)
    {
        item.item = db.Items.Single(i => i.ItemID == item.ItemID);
    }

    return viewModel;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM