I have a simple JavaScript array that I am trying to pass to a controller
function SubmitData()
{
var operationCollection = new Array();
var test1 = { name: "Bill", age: "55", address: "testing" };
operationCollection.push(test1);
var test2 = { name: "Ben", age: "55", address: "testing" };
operationCollection.push(test2);
var test3 = { name: "Flo", age: "55", address: "testing" };
operationCollection.push(test3);
var dataToPost = JSON.stringify(operationCollection);
$.ajax({
type: "POST",
url: "Home/AddPerson",
datatype: JSON,
data: { methodParam: dataToPost },
traditional: true
});
}
The C# controller has a class
public class newEntry
{
public string name { get; set; }
public string age { get; set; }
public string address { get; set; }
}
and the method
public void AddPerson(List<newEntry> methodParam)
{
foreach (newEntry item in methodParam)
{
string name = item.age + item.address;
}
}
When I run the code in debug, the value passed to the controller method is always NULL or 0. I can't seem to get the array to pass correctly. I have read on previous posts that traditional: true will fix this... it doesn't for me though. Has anyone any ideas?
data: dataToPostinstead? You're currently passing an object containing the array instead of the array itself.data: JSON.stringify({ methodParam: operationCollection }),and add theContent-type: application/json; charset=utf-8,options (and note thattraditional: true,is not required). You should also useurl: '@Url.Action("AddPerson", "Home")',to ensure the url is correctly generated