javascript - 如何通过 ajax 将对象数组从 javascript 传递到 asp.net-mvc 函数?

标签 javascript ajax arrays asp.net-mvc post

我有以下构建对象数组的 javascript 代码,我试图通过 ajax post 将其推送到 asp.net-mvc 操作。我想弄清楚下面这个有什么问题?

JavaScript:

var arr = [];
for (var i = 0; i < 5; i++) {
     var obj = {
        statusId: i,
        resizeable: true,
        rows: [1, 2, 3, 4, 5]
      };
      arr.push(obj);
}

$.ajax({
   type: 'POST',
   traditional: true,
   url: '/MyController/UpdateMe',
   data { info: arr },
   success: function () {  
       alert("complete");
   }
});

C# asp.net-mvc Action :

public ActionResult UpdateMe(IEnumerable<UpdateInfo> info)
{
     foreach (var item in info)
     {
          Console.Write(item.statusIs + " has + " item.rows.length() + " items ");
     }
}

public class UpdateInfo
{
    public int statusId {get;set;}
    public bool resizable {get;set;}
    public List<int> rows {get;set;}
}

最佳答案

默认 jQuery.ajax内容类型是 application/x-www-form-urlencoded .这意味着在 url 字符串中发送的参数。在您的情况下,您的数组转换为字符串:object&object&object.... .

要更改此行为,您应该更改 jQuery.ajax 中的 contentType至 application/json并使用 JSON.stringify 将您的 js 对象转换为 json :

$.ajax({
   type: 'POST',
   traditional: true,
   contentType: 'application/json',
   url: '/SchoolDetails/UpdateMe',
   data: JSON.stringify({ info: arr }),
   success: function () {  
      alert("complete");
   }
});

调试中的 Action :

enter image description here

关于javascript - 如何通过 ajax 将对象数组从 javascript 传递到 asp.net-mvc 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770451/

相关文章:

jquery - asp.net MVC ajax 确实回发而不是在我的 div 中渲染部分 View

php - WordPress "admin-ajax.php"404 错误

在 C 中使用 strtok 比较单词

javascript - 创建有序列表并生成输入字段 HTML 和 JS

javascript - 使用另一个数组删除/过滤对象数组

javascript - AngularJS: "isolate scope"还是 "isolated scope"?

javascript - 使用javascript从ajax json获取数组

arrays - 如何像在 Python 中一样在 Julia 中拆分数组?

javascript - 意外的 JS 原型(prototype)行为

javascript - 有免费的可编辑客户端网格吗?