0

我只是想使用 jQuery POST 更新购物车。第一个请求就成功了。但是,它似乎在第二个请求中引发了 500 服务器错误。问题是在我调试之后。第二次尝试渲染视图而不是将 JSON 对象发送到回调函数时的操作结果。下面是我的代码。这是我购物车中的操作结果

    [HttpPost]
    public ActionResult UpdateResultCart(int productId)
    {
        // Retrieve the album from the database
        var addedProduct = _db.Products
            .Single(pr => pr.ProductID == productId);

        // Add it to the shopping cart
        var cart = ShoppingCartModel.GetCart(this.HttpContext);

        cart.AddToCart(addedProduct);

        // Set up our ViewModel
        var shoppingCartData = new ShoppingCartViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal()
        };
        return Json(shoppingCartData);
    }    

这是我的 JavaScript 函数

$(function () {   
$("#AddCartProduct").click(function () {
    var productId = $(this).attr("data-id");
    if (productId != '') {
        // Perform the ajax post
        // Assign handlers immediately after making the request,
        // and remember the jqxhr object for this request
        var jqxhr = $.post("/Cart/UpdateResultCart", { "productId": productId },   function(data) {
            alert("success");
            $('#cart-item').text(": " + data.CartItems.length + " Items");
            $('#total-price').text("Total Price:" + numberToCurrency(data.CartTotal));                
        })
        .done(function() { alert("second success"); })
        .fail(function() { alert("error"); });   
    }
});
});

最后,这是我在局部视图中需要更新的 HTML 元素

@if (Request.IsAuthenticated) {           
<ul>
    <li>             
        @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
        {
            @Html.AntiForgeryToken()
            <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
        }
    </li>
    |
    <li><a href="#">Account</a></li>
    |
    <li>
        <a href="#">Cart</a>
        <label class="cart-item">: 0 Items</label>|
        <label class="total-price">$0.00</label>
    </li>               

</ul>    
} else {
<ul>
    @*<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>*@
    <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>|
    <li><a href="#">Account</a></li>|
    <li>
        <a href="#">Cart</a>
        <label class="cart-item">: 0 Items</label>|
        <label class="total-price">$0.00</label>
    </li>               
</ul>
}

谢谢

4

0 回答 0