leora
leora

Reputation: 196711

What is the correct way to post array of objects using query to an asp.net-mvc controller action?

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?

Upvotes: 5

Views: 13219

Answers (3)

user3559349
user3559349

Reputation:

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() {`

Upvotes: 4

Vinod Bangar
Vinod Bangar

Reputation: 86

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");
    }
});

Upvotes: 1

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

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;}
}

Upvotes: 1

Related Questions