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.
AjaxOptions | HTML attribute |
---|---|
Confirm | data-ajax-confirm |
HttpMethod | data-ajax-method |
InsertionMode | data-ajax-mode |
LoadingElementDuration | data-ajax-loading-duration |
LoadingElementId | data-ajax-loading |
OnBegin | data-ajax-begin |
OnComplete | data-ajax-complete |
OnFailure | data-ajax-failure |
OnSuccess | data-ajax-success |
UpdateTargetId | data-ajax-update |
Url | data-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 :)