尝试将json集合绑定到列表但失败了。不确定为什么。当做这样的单个对象时:
控制器
[HttpPost]
public void Permissions_Set(Permission permissions_JSON)
{
//foreach (var permission_from_view in permissions_JSON)
//{
// //doStuff
//}
}
查看
<script>
var data2 = { id: 1, user_id: 8, project_id: 1, mode: 3 };
$.ajax({
url: "Home/Permissions_Set",
dataType: 'json',
type: 'POST',
data: data2,
success: function () {
}
});
</script>
对象绑定正确。然而,当我使用这样的列表集合时:
控制器
[HttpPost]
public void Permissions_Set(IList<Permission> permissions_JSON)
{
//foreach (var permission_from_view in permissions_JSON)
//{
// //doStuff
//}
}
查看
var data = { permissions_JSON: [{ id: 1, user_id: 8, project_id: 1, mode: 3 }, { id: 1, user_id: 8, project_id: 2, mode: 1 }, { id: 1, user_id: 8, project_id: 3, mode: 1 }] };
$.ajax({
url: "Home/Permissions_Set",
dataType: 'json',
type: 'POST',
data: data,
success: function () {
}
});
它能够弄清楚我的集合中有3个对象,但无法将数据绑定到每个对象。因此,每个对象的int为0(int的默认值)
这是模型
public class Permission
{
public int id { get; set; }
public int user_id { get; set; }
public int project_id { get; set; }
public int mode { get; set; }
}
答案 0 :(得分:1)
设置内容类型并将集合添加到对象中就可以了解
var bob = {permissions_JSON:[{ id: 1, user_id: 8, project_id: 1, mode: 3}]};
request.permissions_JSON = bob;
$.ajax({
url: "Home/Permissions_Set",
dataType: 'json',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(bob),
success: function (data) {
console.log(data);
}
});
答案 1 :(得分:0)
您应将传统参数设置为true:
var data = { permissions_JSON: [{ id: 1, user_id: 8, project_id: 1, mode: 3 }, { id: 1, user_id: 8, project_id: 2, mode: 1 }, { id: 1, user_id: 8, project_id: 3, mode: 1 }] };
$.ajax({
url: "Home/Permissions_Set",
dataType: 'json',
type: 'POST',
data: data,
traditional: true,
success: function () {
}
});