jQuery Unobtrusive Ajax Helpers in ASP.NET Core

Posted by Anuraj on Sunday, September 24, 2017

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 :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Translate
Subscribe


Copyright © 2017 - Anuraj P. 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. Hosted with ❤ by GitHub