简体   繁体   中英

JavaScript Array to MVC Controller

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

    });
}

The C# controller has a class

public class newEntry
{

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

}

and the method

public void AddPerson(List<newEntry> methodParam)
{

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

    }
}

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)

Also as Gavin stated use data: dataToPost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM