I'm trying to pass an array of objects into an MVC controller method using jQuery's ajax() function. When I get into the PassThing() C# controller method, the argument "things" is null. I've tried this using a type of List for the argument, but that doesn't work either. What am I doing wrong?
<script type="text/javascript">
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Xhr/ThingController/PassThing',
data: JSON.stringify(things)
});
});
</script>
public class ThingController : Controller
{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
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)
And in the controller method, use [FromBody]
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 methodCouldn't you just do this?
...and mark your action with
Formatting your data that may be the problem. Try either of these:
Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)
The only way I could get this to work is to pass the JSON as a string and then deserialise it using
JavaScriptSerializer.Deserialize<T>(string input)
, which is pretty strange if that's the default deserializer for MVC 4.My model has nested lists of objects and the best I could get using JSON data is the uppermost list to have the correct number of items in it, but all the fields in the items were null.
This kind of thing should not be so hard.
This is working code for your query,you can use it.
Controler
javascript