In this article I will explain with an example, how to use Newtonsoft library in ASP.Net Core.
Installing Newtonsoft package using Nuget
Configuring the JSON Serializer setting
Model
The Model class consist of the following properties.
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 following 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 class object along with the current Date and Time.
Finally, the
PersonModel class object is returned back as JSON object to the
jQuery AJAX function.
public class HomeController : Controller
{
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 INPUT TextBox and a Button.
Inside the View, the following
jQuery script file is inherited:
1. jquery.min.js
Inside the
document ready event handler, the Button has been assigned with a
jQuery click event handler which when clicked a
jQuery AJAX called is made to the Controller’s action method.
Inside this click event handler, the value of the TextBox is passed as parameter to Controller’s action method.
Finally, 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://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/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
Downloads