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 \"t
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!
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:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
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?
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...
}
If you are using ASP.NET Web API then you should just pass data: JSON.stringify(things)
.
And your controller should look something like this:
public class PassThingsController : ApiController
{
public HttpResponseMessage Post(List<Thing> things)
{
// code
}
}
This is how it works fine to me:
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: '/Controller/action',
data: { "things": things },
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
error: function (response) {
$('#result').html(response);
}
});
With "ContentType" in capital "C".
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.
$.ajax({
type: 'POST',
url: '/Agri/Map/SaveSelfValuation',
data: { json: JSON.stringify(model) },
dataType: 'text',
success: function (data) {
[HttpPost]
public JsonResult DoSomething(string json)
{
var model = new JavaScriptSerializer().Deserialize<Valuation>(json);