Search code examples
javascriptjqueryasp.net-mvc-5actionlinkhtml.actionlink

MVC5 Ajax.ActionLink Loads New Page Instead of Replacing


I know that similar questions have been asked and answered multiple times; for the life of me I cannot determine what I am missing, please bear with me.

I am trying to load a partial view with an editor for an item on the page, and display that editor as a Bootstrap modal, but it always loads to a new page.

_Layout.cshtml references the jQuery bundle:

@Scripts.Render("~/bundles/jquery")

`BundleConfig.RegisterBundles() adds jQuery and unobtrusive ajax:

bundles.Add(new ScriptBundle("~/bundles/jquery")
    .Include("~/Scripts/jquery-{version}.min.js") // <-- must come first
    .Include("~/Scripts/jquery.unobtrusive-ajax.min"));

The Scripts folder contains both files:

Scripts Folder screenshot showing both files

The View has an empty div with the correct id to receive the content

<div id="editor"></div>

I have constructed the ActionLink thusly:

@Ajax.ActionLink(linkText: "Edit",
    actionName: "GetEditor",
    routeValues: new {id = Model.Id},
    ajaxOptions: new AjaxOptions
    {
        OnSuccess = "showEditor",
        UpdateTargetId = "editor",
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "POST"
    })

My JS function just shows the modal:

function showEditor() { $("#editor").modal("show"); };

... and just to see if I can get it to work, I'm returning a simple string from my Controller:

public ActionResult GetEditor(string id) => Content("Success");

Edit 1

In my web.config I have enabled both client side validation and unobtrusive js:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

Edit 2

I have tried to refresh without using the cache (Ctrl+F5) with the same result, and the dev tools show no JavaScript errors. I am getting the same results across all browsers.

What am I forgetting?


Solution

  • Turns out I'm just an idiot:

    I tried to add the unobtrusive validation library manually:

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
    

    ... and it started working. I then thought maybe something was wrong with the bundling - although I was very careful to keep the libraries in the right order....

    bundles.Add(new ScriptBundle("~/bundles/jquery")
      .Include("~/Scripts/jquery-{version}.min.js") 
      .Include("~/Scripts/jquery.unobtrusive-ajax.min"));  // <--- what's missing?
    

    Turns out, full names for javascript files are required.