Не удается получить функцию ajax «добавить в корзину частично» для работы в ASP.NET MVC - PullRequest
0 голосов
/ 25 февраля 2019

Я хочу вызвать функцию ajax, чтобы добавить в свою корзину частичку, которую я сделал, однако, похоже, она не работает.Я думаю, что идентификатор продукта по какой-то причине не связан с ним.Вот код:

 <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 при выборе?

Мой контроллер для 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);
    }

1 Ответ

0 голосов
/ 25 февраля 2019

Возможно, у вас установлен маршрут по умолчанию для id параметров.В этом случае вы можете добавить значение к URL в формате controller/action/{id} и удалить параметры из $.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";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...