How to use jQuery-ajax-unobtrusive in ASP.NET Core

By FoxLearn 9/10/2024 8:44:09 AM   4.42K
To use Microsoft.jQuery.Unobtrusive.Ajax in an ASP.NET Core project, you'll need to follow these steps.

If you try to install Microsoft.jQuery.Unobtrusive.Ajax from Manage Nuget Packages in your Visual Studio, you can't find the library that you have installed. You only can download it offline from the nuget website, then unzip and copy files into your project.

If you want to download Microsoft.jQuery.Unobtrusive.Ajax in Visual Studio you can use bower to install it.

jquery-ajax-unobtrusive asp.net core

How to download Microsoft.JQuery.Unobtrusive.Ajax in ASP.NET Core MVC project?

First, you should download nodejs, then install to your computer.

then, read How to install bower for Visual Studio

Right-clicking on your project, then select Quick Install Package

Enter "Microsoft.jQuery.Unobtrusive.Ajax" at the search box.

jquery-ajax-unobtrusive asp.net core

Finally, click install button.

If you get an error as shown below.

'node' is not recognized as an internal or external command, operable program or batch file

Right-clicking on your computer, then select Properties => Advanced system settings.

Or you can

Open your Control Panel => System and Security => System => Advanced System Settings => Environment Variables.

In "User variables" or "System variables" you need to find variable PATH, then add node.js folder path as value.

Usually for 64bit you can see in C:\Program Files\nodejs. If variable doesn't exists, you need to create it.

computer system properties

Clicking Envirnoment Variables button => Click New button => Add new item as shown below.

add new user variables

Closing your Visual Studio, then reopen it and try to install Microsoft.jQuery.Unobtrusive.Ajax from bower in your Visual Studio.

How to Include jQuery and Unobtrusive Ajax in Your Project

Make sure that both jQuery and the Microsoft.jQuery.Unobtrusive.Ajax scripts are included in your project.

Open your layout file (usually _Layout.cshtml in the Views/Shared directory) and add the following script references in the <head> section or just before the closing </body> tag

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js"></script>

How to use Unobtrusive Ajax in Your Views

@using (Ajax.BeginForm("Index", "BookController", new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "onSuccess",
    OnFailure = "onFailure"
}))
{
    <!-- Form fields here -->
    <input type="submit" value="Submit" />
}

By following these steps, you should be able to successfully integrate Microsoft.jQuery.Unobtrusive.Ajax into your ASP.NET Core project.