-2

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.

Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178

2 Answers2

0

You need to specify a Prefix in your Action like this:

[HttpPost]
public ActionResult TestMethod([Bind(Prefix = "testList")] List<TestViewModel> testList)
{
    // irrelevant code here
}
ataravati
  • 8,891
  • 9
  • 57
  • 89
0

So after 3 hours of banging my head against the wall, I just discovered the solution was to post the data as json. Hopefully this helps someone else in the future:

$.ajax({
    type: 'POST',
    url: '@Url.Action("TestMethod")',
    contentType: 'application/json', // added
    data: JSON.stringify(testList), // changed
    dataType: 'json'
});

Now I can sleep without wondering about this.

David Sherret
  • 101,669
  • 28
  • 188
  • 178