In this article I will explain with an example, how to use jQuery Unobtrusive AJAX in ASP.Net Core Razor Pages.
The POST method of the Razor Page will be called using jQuery AJAX Unobtrusive library and JSON from HTML in ASP.Net Core.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Configuring the JSON Serializer setting
The first step is to configure JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
2. Add the following namespaces.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to:
1. Add MVC Services for Razor Pages.
2. Use Newtonsoft JSON for serialization.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
 
 
Model
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets DateTime.
    ///</summary>
    public string DateTime { get; set; }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
 
Handler method for handling jQuery Unobtrusive AJAX operation
This Handler method handles the call made from the jQuery AJAX function from the View.
Note: The following Handler method handles AJAX calls and hence the return type is set to JsonResult.
 
The value of the name parameter is assigned to the Name property of the PersonModel object along with the Current DateTime and finally the PersonModel object is returned back as JSON to the jQuery AJAX function.
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
 
    [HttpPost]
    public IActionResult OnPost(string name)
    {
        PersonModel person = new PersonModel
        {
            Name = name,
            DateTime = DateTime.Now.ToString()
        };
        return new JsonResult(person);
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML TextBox element and a Submit Button wrapped inside a Form element.
The Form element has been set with the following attributes:
data-ajax – TRUE. In order to enable unobtrusive AJAX for the Form.
data-ajax-method – The HTTP Request method i.e. POST or GET.
data-ajax-success – The name of the JavaScript method that handles the Success event of the AJAX call.
The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_Unobtrusive_Ajax.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" data-ajax="true" data-ajax-method="post" data-ajax-success="OnSuccess">
        <input type="text" id="txtName" name="Name"/>
        <input type="submit" value="Submit"/>
    </form>
 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.unobtrusive-ajax/3.2.5/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        var OnSuccess = function (response) {
            alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
        };
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: jQuery Unobtrusive AJAX example
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads