Ajax ViewComponent 触发多次

Ajax ViewComponent triggering multiple times

我在点击 Ajax 事件时遇到问题,多次触发控制器 action/ViewComponent。

我在单击按钮时使用 Ajax 来调用控制器操作,它将一些数据插入数据库,然后重定向到控制器索引 action/ViewComponent。

每次点击按钮,都会触发越来越多的 Ajax 事件(插入重复数据)。

这是我的设置:

加入购物车 按钮:

<a asp-action="Add" asp-controller="Cart" asp-route-id="@x.ItemID" 
  ajax-call="y" ajax-res="cart" class="btn btn-info">Add to Cart</a>

JS:

 $("a[ajax-call='y']").click(function (event) {
        $(this).attr("ajax-call", "n");
        event.preventDefault();
        var urlCall = $(this).attr("href");
        var divRes = $(this).attr("ajax-res");

        $.ajax({
            type: "GET",
            url: urlCall ,
            async: true,
            success: function (data) {
                $("#" + divRes).html(data);
            }
        });
    });

购物车控制器:

public IActionResult Index() => ViewComponent("Cart");

public IActionResult Add(int id)
{
    ... adds into db ...
    return RedirectToAction("Index");
}

CartViewComponent ~ "Cart":

public IViewComponentResult Invoke()
{
    ... populates view model ...
    return View(Model);
}

我在共享 _Layout.cshtml 中加载我的 JS 文件。我确实在单击 添加到购物车 按钮的地方使用了 PartialView,但我认为这没问题,或者是否以某种方式导致了这个问题?

我最近才开始学习ASP.NET,所以我希望我没有遗漏一些非常简单的东西。

谢谢!

我认为您以某种方式向同一元素添加了多个点击事件。我建议在向元素添加新的点击事件之前清除事件。您可以在单击事件之前使用 .off() 。这将删除所有点击事件并确保您只添加一个。这经常发生在单页应用程序中