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:

  • OnGetMethodName
  • OnPostMethodName
  • OnGetMethodNameAsync
  • OnPostMethodNameAsync

// 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>


Ajax form

Top

List of all data-ajax-* attributes

Top
  • data-ajax

    Boolean value, set to true to activate ajax on the current control

  • data-ajax-url

    The URL to make the request to.

  • data-ajax-method

    The HTTP request method ("Get" or "Post").

  • data-ajax-mode

    The mode that specifies how to insert the response into the target DOM element. Valid values are "before", "after" and "replace".

  • data-ajax-update

    The ID of the DOM element to update by using the response from the server.

  • data-ajax-loading

    The id attribute of an HTML element that is displayed while the Ajax function is loading.

  • data-ajax-loading-duration

    A value, in milliseconds, that controls the duration of the animation when showing or hiding the loading element.

  • data-ajax-confirm

    The message to display in a confirmation window before a request is submitted.

  • data-ajax-begin

    The name of the JavaScript function to call immediately before the page is updated.

  • data-ajax-complete

    The JavaScript function to call when response data has been instantiated but before the page is updated.

  • data-ajax-failure

    The JavaScript function to call if the page update fails.

  • data-ajax-success

    The JavaScript function to call after the page is successfully updated.