In this article I will explain with an example, how to pass (send) list of objects to Controller’s Action method from View using
jQuery AJAX in
ASP.Net MVC.
Model
The Model class consists of following properties.
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { 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 displaying multiple records
Inside this Action method, the Generic List collection of
Customer object is received as parameter and returned to the view in
JSON format.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public JsonResult GetCustomers(List<Customer> customers)
{
return Json(customers);
}
}
View
The View consists of
HTML Button.
Inside the View, the following
jQuery script is inherited:
1. jquery.min.js
When the
Submit button is clicked, a
JSON array is created.
Then, the
JSON array is sent to the Controller using
jQuery AJAX function.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="button" id="btnSubmit" value="Submit" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
var customers = [
{
"CustomerId": 1,
"Name": "John Hammond",
"Country": "United States"
},
{
"CustomerId": 2,
"Name": "Mudassar Khan",
"Country": "India"
},
{
"CustomerId": 3,
"Name": "Suzanne Mathews",
"Country": "France"
},
{
"CustomerId": 4,
"Name": "Robert Schidner",
"Country": "Russia"
}
];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Home/GetCustomers",
data: JSON.stringify(customers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Screenshot
Downloads