I created a simple test scenario with the following view model:
public class TestViewModel
{
public int Number1 { get; set; }
public int Number2 { get; set; }
public int Number3 { get; set; }
}
And ActionResult in the controller:
[HttpPost]
public ActionResult TestMethod(List<TestViewModel> testList)
{
// irrelevant code here
}
Then the following javascript code in the View to post to the Controller:
var testList = [];
for (var i = 0; i < 10; i++) {
testList.push({
Number1: i,
Number2: 2,
Number3: 3
});
}
$.ajax({
type: 'POST',
url: '@Url.Action("TestMethod")',
data: { testList: testList },
dataType: 'json',
//traditional: true
});
In google chrome, it sends the following in the form data:
testList[0][Number1]:0
testList[0][Number2]:2
testList[0][Number3]:3
.
.
testList[9][Number1]:9
testList[9][Number2]:2
testList[9][Number3]:3
Then when it hits the TestMethod in the Controller, testList
is a List<TestModel>
with a length of 10, but all the properties are set to 0
I tried with traditional: true
and when inspecting the traffic it sends the following:
testList:[object Object]
.
.
testList:[object Object]
And testList
is null in TestMethod in the Controller.
Maybe it's just late and I'm not thinking correctly, but what am I doing wrong? Why aren't the values of the individual items in List<TestViewModel> testList
not being set?
I've seen this question: How can I post an array of string to ASP.NET MVC Controller without a form? but that doesn't seem to work for when the list is a custom object.