Using Unobtrusive Ajax In Razor Pages

There are a few demonstrations showing how to use the jQuery Unobtrusive AJAX library in ASP.NET Core, but existing examples tend to feature MVC applications. This article looks at how to use Unobtrusive AJAX in a Razor Pages setting, where it will help to remove a lot of the boilerplate associated with making AJAX requests.

First, what is Unobtrusive AJAX? Well, it has been around for almost 10 years, and was first introduced in ASP.NET MVC 3.0 along with the introduction of the Razor View engine. WebMatrix and the Web Pages framework came out at the same time, but Unobtrusive AJAX has outlasted both of those initiatives. Since then, the library has been added to GitHub, where is forms part of ASPNET Core.

The idea behind Unobtrusive AJAX is that AJAX behaviour is attached to form and anchor elements via HTML5 data-* attributes, instead of binding click event handlers in script blocks. In old MVC, these attributes can be generated from Html helpers: Ajax.BeginForm and Ajax.ActionLink and then setting some AjaxOptions. These particular helpers are not available in ASP.NET Core, but you can add the custom attributes directly to tag helpers instead.

Sounds good. Where do I get it, I hear you ask? It would have been nice to be able to give the new LibMan tool in Visual Studio a try for this task, but Unobtrusive AJAX is not currently available on either of the CDNs that LibMan accesses. So you can either use npm (npm i jquery-ajax-unobtrusive from the Package Manager Console), or you can use one of the many ways that Visual Studio provides to install from Nuget. Once you have it, you can create a new folder for it in wwwroot/lib and copy the file(s) there:

jQuery Unobtrusive AJAX

And then reference it in the page that you want to use it in either directly or as a fallback to a CDN-hosted version:

jQuery Unobtrusive AJAX

If you plan to make use of this library on multiple pages, the Layout page is a better location for referencing it. Either way, now you are ready to roll.

Here is a list of all the custom attributes that control the behaviour of Unobtrusive AJAX: 

HTML attribute Description
data-ajax Must be set to true to activate unobtrusive Ajax on the target element.
data-ajax-confirm Gets or sets the message to display in a confirmation window before a request is submitted.
data-ajax-method Gets or sets the HTTP request method ("Get" or "Post").
data-ajax-mode Gets or sets the mode that specifies how to insert the response into the target DOM element.
data-ajax-loading-duration Gets or sets a value, in milliseconds, that controls the duration of the animation when showing or hiding the loading element.
data-ajax-loading Gets or sets the id attribute of an HTML element that is displayed while the Ajax function is loading.
data-ajax-begin Gets or sets the name of the JavaScript function to call immediately before the page is updated.
data-ajax-complete Gets or sets the JavaScript function to call when response data has been instantiated but before the page is updated.
data-ajax-failure Gets or sets the JavaScript function to call if the page update fails.
data-ajax-success Gets or sets the JavaScript function to call after the page is successfully updated.
data-ajax-update Gets or sets the ID of the DOM element to update by using the response from the server.
data-ajax-url Gets or sets the URL to make the request to.

 

As a reminder, these attributes are only effective on form and anchor elements. This first example looks at thow to apply those attributes to a form tag helper to enable asynchronous posting of the values:

And that is all it takes. When the form is submitted, the request will be initiated by AJAX. There is no action specified, so the form values will be posted to the URL of the page where they can be processed in an OnPost handler. Note that the form's method attribute is also specified as post, along with the custom attribute.  In the absence of an action attribute being supplied this is necessary to ensure that the request verification token hidden field is generated and included in the form. Without this, form posts will result in a 400 Bad Request status code because they will fail the request verification test.

Unobtrusive AJAX

You can use the data-ajax-confirm attribute to specify the message that a confirm prompt displays on form submission, and the data-ajax-complete attribute to specify a callback function that should be fired when the post completes:

In this example, the input is bound to a PageModel property and then returned as a string:

... resulting in the following workflow:

Unobtrusive AJAX

The next example illustrates partial update being initiated by a click on an anchor tag. Here's the HTML:

The data-ajax-url attribute is used to specify the URL for the AJAX request. The data-ajax-update attribute takes a jQuery selector representing the element that should have its content replaced with the response.

This example uses a named handler to return the content of a partial view:

Finally here is the content of the partial view:

Summary

This has been quick look at how useful the Unobtrusive AJAX library can be in an ASP.NET Core Razor Pages application. It targets the anchor and form elements, and will reduce the boilerplate code that you write to perform many common AJAX-related tasks. It is a very small library - only 4kb when minimised. It is dependent on jQuery, so if you are already using that (e.g. as part of Bootstrap), the additional overhead is tiny. You can see more examples of using Unobtrusive AJAX in Razor Pages here.