In this article I will explain with an example, how to use XmlHttpRequest (XHR) and AJAX in ASP.Net Core MVC.
This article will explain how to make a POST call to Controller’s Action method using JavaScript XmlHttpRequest (XHR) and AJAX in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core MVC, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
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; }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling JavaScript XmlHttpRequest (XHR) AJAX operation
This Action method handles the call made from the JavaScript XmlHttpRequest (XHR) AJAX function from the View.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.
 
The PersonModel object is accepted as parameter and the Current DateTime is assigned to its DateTime property.
Finally, the PersonModel object is returned back as JSON to the JavaScript XmlHttpRequest (XHR) AJAX function.
Note: The FromBody attribute is used for model-binding the data sent from XmlHttpRequest (XHR) request.
 
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod([FromBody] PersonModel person)
    {
        person.DateTime = DateTime.Now.ToString();
        return Json(person);
    }
}
 
 
View
The View consists of an HTML TextBox element and a Button. The Button has been assigned a JavaScript OnClick event handler and when the Button is clicked, the ShowCurrentTime JavaScript method is called.
Inside the ShowCurrentTime JavaScript method, the URL for the XmlHttpRequest (XHR) AJAX call is set to the Controller’s Action method i.e. /Home/AjaxMethod.
The Controller’s Action method is called using JavaScript XmlHttpRequest (XHR) AJAX request and the value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="text" id="txtName"/>
    <input type="button" id="btnGet" value="Get Current Time" onclick="ShowCurrentTime()"/>
    <script type="text/javascript">
        function ShowCurrentTime() {
            var person = {};
            person.Name = document.getElementById("txtName").value;
 
            var request;
            if (window.XMLHttpRequest) {
                //New browsers.
                request = new XMLHttpRequest();
            }
            elseif (window.ActiveXObject) {
                //Old IE Browsers.
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (request != null) {
                var url = "/Home/AjaxMethod";
                request.open("POST", url, false);
                request.setRequestHeader("Content-Type", "application/json");
                request.onreadystatechange = function () {
                    if (request.readyState == 4 && request.status == 200) {
                        var response = JSON.parse(request.responseText);
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    }
                };
                request.send(JSON.stringify(person));
            }
        }
    </script>
</body>
</html>
 
 
Configuring the JSON Serializer setting
The above program will work but you will see undefined values in the JavaScript Alert Message Box.
Using XmlHttpRequest (XHR) and AJAX in ASP.Net Core
 
In order to resolve it, the JSON Serializer settings need to be configured in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
2. Add the following namespace.
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to use Newtonsoft library for JSON serialization.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
 
Note: For more details, please refer my article [SOLVED] LowerCase JSON Property Names in ASP.Net Core.
 
 
Screenshot
Using XmlHttpRequest (XHR) and AJAX in ASP.Net Core
 
 
Downloads