5

I have an array of data:

var myArray = [{"id": 1, "name", "John"},{"id": 2, "name", "Joe"},{"id": 3, "name", "Bill"}] 

 $.post("/MyController/Update", myArray, function (data) {
       alert("Complete");
 });

and here is my asp.net-mvc controller action

public ActionResult Update(List<Person> people)
{
     return Json(new {Success = true});
}

public class Person
{
    public int id {get;set;}
    public string name {get;set;}
}

I also tried:

 var paramString = JSON.stringify({ people: myArray});

 $.post("/MyController/Update", paramString , function (data) {
        alert("Complete");
  });

but when i look at the people parameter on the server, I either see:

  1. null
  2. array of 3 items but the values of Id are always 0 and the value of Name is always an empty string

any suggestions on what I am doing wrong here?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 1
    possible duplicate of [jQuery Ajax POSTing array to ASP.NET MVC Controller](http://stackoverflow.com/questions/4402036/jquery-ajax-posting-array-to-asp-net-mvc-controller) – Ilya Sulimanov Mar 23 '15 at 11:42

3 Answers3

4

You javascipt object properties do not have indexers, so you need to use the ajax contentType: "application/json" option and stringify the object

var myArray = [{"id": 1, "name", "John"},{"id": 2, "name", "Joe"},{"id": 3, "name", "Bill"}] 

$.ajax({
  type: 'post',
  url: '@Url.Action("Update", "MyController")', // don't hardcode your url's!
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({ people: myArray }),
  success: function (data) {
    ....
  }
})

Side note. The following object would post back

var myArray = { people[0].id: 1, people[0].name: "John", people[1].id: 2, people[1].name: "Joe" }

using

$.post('@Url.Action("Update", "MyController")', myArray, function() {`
1

My personal favorite is using JSON.NET (available through NuGet).

You may define on your Action that it would expect a JObject or JArray.

Then in the Action you just cast your input to your expected type.

From js perspective you just do your post normally.

Example:

public ActionResult Update(JArray input)
{
     var persons = input.Select(x=>x.ToObject<Person>()) // This will return an `Enumerable<Person>`
     //Do your other stuff here
     return Json(new {Success = true});
}

public class Person
{
    public int id {get;set;}
    public string name {get;set;}
}
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
1

try this

First change your array like this

var myArray = [{"id": 1, "name": "John"},{"id": 2, "name": "Joe"},{"id": 3, "name": "Bill"}] ;

And then try posting using $.ajax()

$.ajax({
    url: "/MyController/Update",
    type: "POST",
    datatype: 'json',
    contentType: "application/json",
    data: JSON.stringify(myArray),
    success: function (data) {
          alert("Complete");
    }
});