2

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?

3
  • 3
    Have you tried passing it as data: dataToPost instead? You're currently passing an object containing the array instead of the array itself. Commented Oct 13, 2016 at 16:48
  • 1
    It needs to be data: JSON.stringify({ methodParam: operationCollection }), and add the Content-type: application/json; charset=utf-8, options (and note that traditional: true, is not required). You should also use url: '@Url.Action("AddPerson", "Home")', to ensure the url is correctly generated Commented Oct 13, 2016 at 20:48
  • Thanks Stephen - that sorted it. Commented Oct 17, 2016 at 7:42

1 Answer 1

2

Try adding this to the signature of your method:

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

Also as Gavin stated use data: dataToPost

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.