使用查询将对象数组发布到 asp.net-mvc 控制器操作的正确方法是什么?

leo*_*ora 5 javascript ajax asp.net-mvc jquery http-post

我有一组数据:

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

 $.post("/MyController/Update", myArray, function (data) {
       alert("Complete");
 });
Run Code Online (Sandbox Code Playgroud)

这是我的 asp.net-mvc 控制器操作

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

public class Person
{
    public int id {get;set;}
    public string name {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

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

 $.post("/MyController/Update", paramString , function (data) {
        alert("Complete");
  });
Run Code Online (Sandbox Code Playgroud)

但是当我查看服务器上的 people 参数时,我要么看到:

  1. 无效的
  2. 包含 3 项的数组,但 Id 的值始终为 0,Name 的值始终为空字符串

关于我在这里做错了什么有什么建议吗?

小智 4

您的 javascipt 对象属性没有索引器,因此您需要使用 ajaxcontentType: "application/json"选项并对对象进行字符串化

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) {
    ....
  }
})
Run Code Online (Sandbox Code Playgroud)

边注。以下对象将回发

var myArray = { people[0].id: 1, people[0].name: "John", people[1].id: 2, people[1].name: "Joe" }
Run Code Online (Sandbox Code Playgroud)

使用

$.post('@Url.Action("Update", "MyController")', myArray, function() {`
Run Code Online (Sandbox Code Playgroud)