Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things });
Here is the complete code.
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
There are two things I learned from this:
The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.
To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.
I hope this helps someone else!
Couldn't you just do this?
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
function () {
$('#result').html('"PassThings()" successfully called.');
});
...and mark your action with
[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
// do stuff with things here...
}
I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.
In my case the solution was as follows:
Script - stringify the original array (without using a named property)
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
And in the controller method, use [FromBody]
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Failures include:
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
Notes
dataType
is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).List<Thing>
also works in the controller method