JavaScript数组到MVC控制器 [英] JavaScript Array to MVC Controller

查看:88
本文介绍了JavaScript数组到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple JavaScript array that I am trying to pass to a controller

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 将解决这个问题......但它并不适合我。有没有人有任何想法?

When I run the code in debug, the value passed to the controller method is always NULL or 0. I can't seem to get the array to pass correctly. I have read on previous posts that traditional: true will fix this... it doesn't for me though. Has anyone any ideas?

推荐答案

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

Try adding this to the signature of your method:

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

同样,Gavin声明使用数据:dataToPost

Also as Gavin stated use data: dataToPost

这篇关于JavaScript数组到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆