我有以下构建对象数组的 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 :
关于javascript - 如何通过 ajax 将对象数组从 javascript 传递到 asp.net-mvc 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770451/