【问题标题】:JavaScript Array to MVC ControllerJavaScript 数组到 MVC 控制器
【发布时间】:2016-10-13 16:45:20
【问题描述】:

我有一个简单的 JavaScript 数组,我试图将它传递给控制器​​

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

    });
}

C# 控制器有一个类

public class newEntry
{

    public string name { get; set; }
    public string age { get; set; }
    public string address { get; set; }

}

方法

public void AddPerson(List<newEntry> methodParam)
{

    foreach (newEntry item in methodParam)
    {
      string name =  item.age + item.address;

    }
}

当我在调试中运行代码时,传递给控制器​​方法的值始终为 NULL 或 0。我似乎无法让数组正确传递。我在以前的帖子中读过traditional: true 会解决这个问题……但它不适合我。有人有什么想法吗?

【问题讨论】:

  • 您是否尝试将其作为data: dataToPost 传递?您当前正在传递一个包含数组而不是数组本身的对象。
  • 它必须是data: JSON.stringify({ methodParam: operationCollection }), 并添加Content-type: application/json; charset=utf-8, 选项(注意traditional: true, 不是必需的)。您还应该使用url: '@Url.Action("AddPerson", "Home")', 来确保正确生成 url
  • 谢谢斯蒂芬 - 排序它。

标签: javascript ajax asp.net-mvc


【解决方案1】:

尝试将此添加到您的方法的签名中:

[HttpPost]
public void AddPerson(List<newEntry> methodParam)

正如 Gavin 所说,使用 data: dataToPost

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2013-03-24
    • 2014-11-21
    相关资源
    最近更新 更多