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

时间:2015-03-23 11:34:25

标签: javascript jquery ajax asp.net-mvc http-post

我有一系列数据:

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

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

这是我的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;}
}

我也尝试过:

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

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

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

  1. 包含3个项目的数组,但Id的值始终为0,Name的值始终为空字符串
  2. 我在这里做错了什么建议?

3 个答案:

答案 0 :(得分:4)

你javascipt对象属性没有索引器,所以你需要使用ajax contentType: "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) {
    ....
  }
})

旁注。以下对象将回发

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

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

答案 1 :(得分:1)

我个人最喜欢的是使用JSON.NET(可通过NuGet获得)。

您可以在行动中定义预期JObjectJArray

然后在Action中,您只需将输入转换为预期类型。

从js角度来看,你只需正常发帖。

示例:

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

答案 2 :(得分:1)

试试这个

首先像这样更改你的数组

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

然后尝试使用$ .ajax()

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