ajaxasp.net-coreunobtrusive-ajax

Unobtrusive Ajax returns "The name 'Ajax' does not exist in the current context" in ASP.NET Core


If I start a new project in ASP.NET 4.5, select Manage NuGet packages, search for Ajax, then install Unobtrusive Ajax, I can then go into my .cshtml file and type @Ajax.___, e.g. @Ajax.beginForm.

If I create a new project with ASP.NET Core, I cannot, where instead it gives me this error:

The name 'Ajax' does not exist in the current context

I want to make a Form with an Ajax call as you could do in ASP.NET, such as:

@using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { 
    HttpMethod = "POST", UpdateTargetId = "divEmp" })) {
    ...
    }
}

In the above, I can see that Ajax is an object of type AjaxHelper which comes from `System.Web.MVC.WebViewPage... so maybe it was never meant to be available for .NET Core?

Anyone know what else I can try?


Solution

  • While the Ajax.BeginForm() methods do not work in ASP.NET Core, the actual Unobtrusive Ajax HTML does. The C# methods just help generate the HTML form tags. Forgive me if this syntax is wrong; this is from memory, but you get the idea:

    @using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
    {
        //form content
    }
    

    becomes

    <form asp-action="EmployeeMaster" asp-controller="Home" method="POST" data-ajax="true" data-ajax-update="divEmp">
        <!-- form content-->
    </form>
    

    NOTE: The above HTML STILL needs the Unobtrusive Ajax JS files for it to wire up these data-* attributes correctly. This is not a part of ASP.NET Core MVC.