Question

In _Layout.cshtml:

@RenderBody()
@Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js")

Running the script activates all the @Ajax.ActionLink in index.cshtml. Some ajax action links load a partial view via ajax, and these partial views include more ajax action links. These new ajax action links are not activated because jquery.unobtrusive-ajax.js was run before they are on the page.

My solution was to simply run the script again on the partial view.

In _PartialView.cshtml:

@Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js")

This however causes @Ajax.ActionLink in index.cshtml to be activated a second time. If I click on any of these ajax action links, their corresponding actions runs twice.

How can I activate new ajax action links in partial views without reactivating existing ajax action links?

Was it helpful?

Solution

Unless you are using some very old version of the jquery.unobtrusive-ajax.js script what you describe shouldn't be the case. The reason why this shouldn't be the case is because the jquery.unobtrusive-ajax.js that comes with ASP.NET MVC 4 uses the jQuery .delegate or in most recent versions the .on() function to subscribe to the click events of the Ajax.* elements. This means that the click handler will be executed even for elements that are not initially present in the DOM but are loaded later using AJAX calls for example.

And in the latest version it uses the .on method:

$(document).on("click", "a[data-ajax=true]", function (evt) {
    evt.preventDefault();
    asyncRequest(this, {
        url: this.href,
        type: "GET",
        data: []
    });
});

Notice how it subscribes to the .click event in a lively manner to all anchors having the data-ajax="true" attribute. And it will do that even for anchors that are added later to the DOM.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top