jQuery Unobtrusive Ajax Helpers in ASP.NET Core

September 24, 2017 by Anuraj

ASP.NET Core JQuery Unobtrusive

This post is about getting jQuery Unobtrusive Ajax helpers in ASP.NET Core. AjaxHelper Class represents support for rendering HTML in AJAX scenarios within a view. If you’re migrating your existing ASP.NET MVC project to ASP.NET Core MVC, but there is no tag helpers available out of the box as replacement. Instead ASP.NET Core team recommends data-* attributes. All the existing @Ajax.Form attributes are available as data-* attributes.

To use this first, you need to reference jquery and jquery.unobtrusive-ajax scripts, you can download and install it via bower. Here is the command to install the script libraries via bower - bower install Microsoft.jQuery.Unobtrusive.Ajax.

Once you install the script, you can reference it in _layout.cshtml file like this.

<script src="~/lib/Microsoft.jQuery.Unobtrusive.Ajax/jquery.unobtrusive-ajax.min.js"></script>

Here is the attributes which can be used to migrate @Ajax.Form helpers.

AjaxOptionsHTML attribute
Confirmdata-ajax-confirm
HttpMethoddata-ajax-method
InsertionModedata-ajax-mode
LoadingElementDurationdata-ajax-loading-duration
LoadingElementIddata-ajax-loading
OnBegindata-ajax-begin
OnCompletedata-ajax-complete
OnFailuredata-ajax-failure
OnSuccessdata-ajax-success
UpdateTargetIddata-ajax-update
Urldata-ajax-url

You can add these attributes with the Form element like this.

<form asp-controller="Home" asp-action="SaveForm" data-ajax="true" data-ajax-method="POST">
</form>

Here is the code, which will display a progress indicator while submitting the form, and once it is completed, success or failed, it will show alert message.

var results = $("#Results");
var onBegin = function(){
    results.html("<img src=\"/images/ajax-loader.gif\" alt=\"Loading\" />");
};

var onComplete = function(){
    results.html("");
};

var onSuccess = function(context){
    alert(context);
};

var onFailed = function(context){
    alert("Failed");
};

And here is the HTML form.

<form asp-controller="Home" asp-action="SaveForm"
    data-ajax-begin="onBegin" data-ajax-complete="onComplete"
    data-ajax-failure="onFailed" data-ajax-success="onSuccess"
    data-ajax="true" data-ajax-method="POST">
    <input type="submit" value="Save" class="btn btn-primary" />
    <div id="Results"></div>
</form>

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub