In this article I will explain with an example, how to call Controller using JavaScript and AJAX in ASP.Net MVC Razor.
The Controller’s Action method will be called using JavaScript XmlHttpRequest (XHR) and JSON from View in ASP.Net MVC Razor.
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 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 JavaScript XmlHttpRequest (XHR) AJAX function.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod(string name)
{
PersonModel person = new PersonModel
{
Name = name,
DateTime = DateTime.Now.ToString()
};
return Json(person);
}
}
View
Inside the View, in the very first line the PersonModel class is declared as Model for the 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.
@model XHR_AJAX_MVC.Models.PersonModel
@{
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 name = document.getElementById("txtName").value;
var request;
if (window.XMLHttpRequest) {
//New browsers.
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
//Old IE Browsers.
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request != null) {
var url = "/Home/AjaxMethod";
request.open("POST", url, false);
var params = "{name: '" + name + "'}";
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(params);
}
}
</script>
</body>
</html>
Screenshot
Downloads