使用查询向asp.net-mvc控制器操作发布对象数组的正确方法是什么? [英] What is the correct way to post array of objects using query to an asp.net-mvc controller action?

查看:432
本文介绍了使用查询向asp.net-mvc控制器操作发布对象数组的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据数组:

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控制器动作

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

我也尝试过:

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

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

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

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


  1. null

  2. 3个项目的数组,但Id的值始终为0,Name的值始终为空string

我在这里做错了什么建议?

any suggestions on what I am doing wrong here?

推荐答案

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

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) {
    ....
  }
})

S. ide note。以下对象将回发

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

使用

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

这篇关于使用查询向asp.net-mvc控制器操作发布对象数组的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆