在没有表单的情况下将对象列表发布到控制器

时间:2013-07-17 04:05:57

标签: c# asp.net-mvc asp.net-mvc-4

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

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
}

然后将视图中的以下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
});

在Google Chrome中,它会在表单数据中发送以下内容:

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,但所有属性都设置为0

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

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

并且testList在Controller中的TestMethod中为空。

也许现在已经很晚了,我思路不正确,但我做错了什么?为什么List<TestViewModel> testList中的各个项目的值没有设置?

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

现在我可以睡不着觉。

相关问题