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

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

本文关键字:操作 控制器 net-mvc 是什么 方法 asp 查询 对象 数组      更新时间:2023-09-26

我有一个数据数组:

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

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

  1. null
  2. 由3个项组成的数组,但Id的值始终为0,Name的值始终是空字符串

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

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

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

您可以在Action中定义它将期望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;}
}

尝试这个

首先像这个一样改变你的阵列

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