Ajax Request Using Inline Attributes
Ajax requsts can be made using inline data-ajax-* attributes that can be applied to anchor tags or forms as well.
Different application methods has been demonstrated below.
Basic Setup
1. Include jquery libraries
<!-- include jquery libraries -->
@section Scripts {
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-ajax-unobtrusive@3.2.6/dist/jquery.unobtrusive-ajax.min.js"></script>
}
2. Create backend method
Create a backend method to handle the ajax call and return appropriate data. Make sure to name the method as one of the below formats:
OnGetMethodNameOnPostMethodNameOnGetMethodNameAsyncOnPostMethodNameAsync
// Simple method to return current date
public ContentResult OnGetCurrentDate()
{
return Content($"{DateTime.Now}");
}
3. Add data-ajax-* attributes
data-ajax-* attributes will setup the current anchor tag or form to do the ajax call and update the target element.
See list of all data-ajax-* attributes.
<a href="#" data-ajax="true" data-ajax-update="#updateDiv" data-ajax-url="/MethodName">Sample Ajax Link</a>
4. Create the element that will be updated by ajax call result
<div id="updateDiv"></div>
Simple ajax link
TopAjax form
TopList of all data-ajax-* attributes
Top
-
data-ajaxBoolean value, set to true to activate ajax on the current control
-
data-ajax-urlThe URL to make the request to.
-
data-ajax-methodThe HTTP request method ("Get" or "Post").
-
data-ajax-modeThe mode that specifies how to insert the response into the target DOM element. Valid values are "before", "after" and "replace".
-
data-ajax-updateThe ID of the DOM element to update by using the response from the server.
-
data-ajax-loadingThe id attribute of an HTML element that is displayed while the Ajax function is loading.
-
data-ajax-loading-durationA value, in milliseconds, that controls the duration of the animation when showing or hiding the loading element.
-
data-ajax-confirmThe message to display in a confirmation window before a request is submitted.
-
data-ajax-beginThe name of the JavaScript function to call immediately before the page is updated.
-
data-ajax-completeThe JavaScript function to call when response data has been instantiated but before the page is updated.
-
data-ajax-failureThe JavaScript function to call if the page update fails.
-
data-ajax-successThe JavaScript function to call after the page is successfully updated.