gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:48:30 24 4
gpt4 key购买 nike

我有以下构建对象数组的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com