0

jQuery POST を使用してカートを更新しようとしています。最初のリクエストで成功です。ただし、2 番目のリクエスト内で 500 サーバー エラーがスローされるようです。問題は、デバッグした後です。JSON オブジェクトをコールバック関数に送信する代わりに、2 回目にビューをレンダリングしようとしたときのアクション結果。これが私のコードです。これがカート内のアクション結果です

    [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