Search code examples
javascriptjqueryasp.netajaxasp.net-core-viewcomponent

Ajax ViewComponent triggering multiple times


I have an issue with an on-click Ajax event, triggering a Controller action/ViewComponent multiple times.

I used Ajax on a button-click to call a Controller Action, which inserts some data into the database, and then redirects to the Controller Index action/ViewComponent.

Everytime the button is clicked, more and more Ajax events are triggered (duplicate data inserted).

Here's my setup:

Add to Cart Button:

<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);
            }
        });
    });

CartController:

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);
}

I load my JS files in the shared _Layout.cshtml. I do use a PartialView from where the Add to Cart button is being clicked though, I think that's okay or is that someway causing this issue?

I started learning ASP.NET only recently, so I hope I'm not missing something very simple.

Thanks!


Solution

  • I think somehow you are adding multiple click events to the same element. I suggest clearing the events before adding a new click event to the element. You can use .off() just before you do click event. That will remove all click events and make sure you are only adding one. This often happens in single page applications