Home > Back-end >  Ajax call doesn't seem to work in ASP.NET Core
Ajax call doesn't seem to work in ASP.NET Core

Time:11-06

I have the following view, partial view and controller:

@using CustomersAJAX.Models
@model Tuple<List<Customer>, Customer>

@{
    AjaxOptions ajaxOptions = new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "customerInfo"
    };

}

@using (Html.AjaxBeginForm("OnSelectCustomer", "Customer", ajaxOptions))
{
    @Html.AntiForgeryToken();

    var selected = false;

    foreach (var customer in Model.Item1)
    {
        if (Model.Item2 == customer)
        {
            selected = true;
        }
        else
        {
            selected = false;
        }

        @Html.RadioButton("CustomerNumber", customer.ID, selected);
        @Html.Label(customer.Name);
        <br />
    }
    <input type="submit" id="SumbitButton" value="Submit Details" />

}

<div id="customerInfo">
    @await Html.PartialAsync("~/Views/Shared/_CustomerDetails.cshtml", Model.Item2)
</div>

@model CustomersAJAX.Models.Customer

<h3>Customer Details</h3>
@Html.DisplayNameFor(m => Model.Name):@Html.DisplayFor(m => Model.Name)
<br />
@Html.DisplayNameFor(m => Model.Age):@Html.DisplayFor(m => Model.Age)
<br />
<p>Updated at @DateTime.Now</p>


public class CustomerController : Controller
{
        List<Customer> customers;

        public CustomerController()
        {
            customers = new List<Customer>
            {
                new Customer(0, "Sherry", 37),
                new Customer(1, "Tim", 12),
                new Customer(2, "Charlene", 98),
                new Customer(3, "Dane", 24),
                new Customer(4, "Elijah", 51),
                new Customer(5, "Howard", 64),
                new Customer(6, "Dave", 34)
            };
        }

        public IActionResult Index()
        {
            Tuple<List<Customer>, Customer> tuple = new Tuple<List<Customer>, Customer>(customers, customers[0]);

            return View("Customer", tuple);
        }

        [HttpPost]
        public IActionResult OnSelectCustomer(string CustomerNumber)
        {
            return PartialView("_CustomerDetails", customers[int.Parse(CustomerNumber)]);
        }
}

It works, however, the Ajax part ('_CustomerDetails' view) renders as separate view like in case there was no Ajax, and not as part of the Customer view as it is supposed to do.

I have the following package installed:

<PackageReference Include="AspNetCore.Unobtrusive.Ajax" Version="1.1.3" />

And in _Layout.cshtml body I reference the following:

<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

CodePudding user response:

Please check if your jquery.validate.unobtrusive.js exists in wwwroot/lib/jquery-validation-unobtrusive. When you install the AspNetCore.Unobtrusive.Ajax server side library, it does not mean you also have installed the jquery.validate.unobtrusive.js which is client side library in local.

If you just install the AspNetCore.Unobtrusive.Ajax, you can use @Html.RenderUnobtrusiveAjaxScript() to call the jquery.validate.unobtrusive.js.

Or you can enter image description here


The whole working way by using AspNetCore.Unobtrusive.Ajax should be like below:

  1. Install AspNetCore.Unobtrusive.Ajax nuget package:

PM> Install-Package AspNetCore.Unobtrusive.Ajax

  1. Add Service and Middleware in Startup.cs:

     public void ConfigureServices(IServiceCollection services)
     {
         //...
         services.AddUnobtrusiveAjax(); 
         //services.AddUnobtrusiveAjax(useCdn: true, injectScriptIfNeeded: false);
         //...
     }
    
     public void Configure(IApplicationBuilder app)
     {
     //...
         app.UseStaticFiles();
    
         //It is required for serving 'jquery-unobtrusive-ajax.min.js' embedded script file.
         app.UseUnobtrusiveAjax(); //It is suggested to place it after UseStaticFiles()
         //...
     }
    
  2. Add Script Tag in _Layout.cshtml:

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    
    <!--Place it at the end of body and after jquery-->
    
     @Html.RenderUnobtrusiveAjaxScript()
    
    <!-- Or you can reference your local script file -->
    
     @RenderSection("Scripts", required: false)
     </body>
     </html>
    
  • Related