无法让我的 ajax "add to Cart Partial" 函数在 MVC ASP.NET 工作



我想调用一个ajax函数以添加到我的购物车部分中,但是它似乎无法正常工作。我认为由于某种原因,产品ID没有链接到它。这是代码:

 <div class="addtocart">
            <a href="#" class="addtocart">Add to cart</a>
            <span class="ajaxmsg">The product has been added to your cart. </span>
  </div>
<script>
$(function () {

/*
* Add to cart
*/
$("a.addtocart").click(function (e) {
    e.preventDefault();
    $("span.loader").addClass("ib");
    var url = "/cart/AddToCartPartial";
    $.get(url, { id: @Model.Id }, function (data) {
        $(".ajaxcart").html(data);
    }).done(function () {
        $("span.loader").removeClass("ib");
        $("span.ajaxmsg").addClass("ib");
        setTimeout(function () {
            $("span.ajaxmsg").fadeOut("fast");
            $("span.ajaxmsg").removeClass("ib");
        }, 1000);
    });
});

  </script>

我找到了一个解决方案,但是当我使用此链接时,它可以使用,但是它需要我不想要的addtocartpartial。

@Html.ActionLink("Test", "AddtoCartPartial", "Cart", new { id = Model.Id }, new { @class = "addtocart" })

是否有另一种调用ajax脚本的方式,或者有一种避免链接带我到选择的链接的方法?

我的addtocartpartial控制器是:

   public ActionResult AddToCartPartial(int id)
    {
        // Init CartVM list
        List<CartVM> cart = Session["cart"] as List<CartVM> ?? new List<CartVM>();
        // Init CartVM
        CartVM model = new CartVM();
        using (Db db = new Db())
        {
            // Get the product
            ProductDTO product = db.Products.Find(id);
            // Check if the product is already in cart
            var productInCart = cart.FirstOrDefault(x => x.ProductId == id);
            // If not, add new
            if (productInCart == null)
            {
                cart.Add(new CartVM()
                {
                    ProductId = product.Id,
                    ProductName = product.Name,
                    Quantity = 1,
                    Price = product.Price,
                    Image = product.ImageName
                });
            }
            else
            {
                // If it is, increment
                productInCart.Quantity++;
            }
        }
        // Get total qty and price and add to model
        int qty = 0;
        decimal price = 0m;
        foreach (var item in cart)
        {
            qty += item.Quantity;
            price += item.Quantity * item.Price;
        }
        model.Quantity = qty;
        model.Price = price;
        // Save cart back to session
        Session["cart"] = cart;
        // Return partial view with model
        return PartialView(model);
    }

您可能具有id参数的默认路由。在这种情况下,您可以以格式controller/action/{id}将值附加到URL,然后从$.get中删除参数。下面的代码可能对您有用:

var url = "/cart/AddToCartPartial/" + "@Model.Id";
$.get(url, function (data) {
    $(".ajaxcart").html(data);
}).done(function () {
    // ... other code
});

或者您可以尝试使用查询参数样式附加id

var url = "/cart/AddToCartPartial?id=" + "@Model.Id";

最新更新