-2

我使用以下视图模型创建了一个简单的测试场景:

public class TestViewModel
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
}

控制器中的 ActionResult :

[HttpPost]
public ActionResult TestMethod(List<TestViewModel> testList)
{
    // irrelevant code here
}

然后将 View 中的以下 javascript 代码发布到 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
});

在谷歌浏览器中,它在表单数据中发送以下内容:

testList[0][Number1]:0
testList[0][Number2]:2
testList[0][Number3]:3
.
.
testList[9][Number1]:9
testList[9][Number2]:2
testList[9][Number3]:3

然后当它碰到Controller中的TestMethod时,testListList<TestModel>一个长度为10的a,但是所有的属性都设置为0

我尝试使用traditional: true并在检查流量时发送以下内容:

testList:[object Object]
.
.
testList:[object Object]

并且testList在 Controller 的 TestMethod 中为 null。

也许只是太晚了,我的想法不正确,但我做错了什么?为什么没有List<TestViewModel> testList设置单个项目的值?

我已经看到了这个问题:How can I post a array of string to ASP.NET MVC Controller without a form?但是当列表是自定义对象时,这似乎不起作用。

4

2 回答 2

0

您需要在 Action 中指定一个前缀,如下所示:

[HttpPost]
public ActionResult TestMethod([Bind(Prefix = "testList")] List<TestViewModel> testList)
{
    // irrelevant code here
}
于 2013-07-17T04:13:09.927 回答
0

因此,经过 3 个小时的头撞墙后,我才发现解决方案是将数据发布为 json。希望这对将来的其他人有所帮助:

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

现在我可以毫无疑问地睡觉了。

于 2013-07-17T04:21:01.187 回答