In this article I will explain with an example, how to call Controller using
jQuery AJAX in ASP.Net Core (.Net Core 8) MVC.
Model
You will need to import the following namespaces.
public class PersonModel
{
public string Name { get; set; }
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 POST operation
Inside this Action method, 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.
Finally, the
PersonModel object is returned back as
JSON 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
HTML Markup
Inside the 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.
Then, the URL for the
jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod.
Finally, 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/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);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Screenshot
Downloads