In this article I will explain with an example, how to get Current Date and Time from Controller using jQuery AJAX in ASP.Net Core MVC.
The Current Date and Time will be determined inside the Controller’s Action method which will be later sent to the View for display using jQuery AJAX in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Configuring the JSON Serializer setting
The first step is to configure the JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core MVC: Get Current Date and Time from Controller
 
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());
}
 
 
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 jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action 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 HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod(string name)
    {
        PersonModel person = new PersonModel
        {
            Name = name,
            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 jQuery click event handler and when the Button is clicked a jQuery AJAX called is made to the Controller’s action method.
The URL for the jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod. 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"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: { "name": $("#txtName").val() },
                    success: function (response) {
                        alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                   }
                });
            });
        });
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: Get Current Date and Time from Controller
 
 
Downloads