我试图通过JSON将一些数据发送到MVC控制器操作:
出于某种原因,这有效:
var items = [];
$("input:checked").each(function () { items.push($(this).val()); });
//This works
$.ajax({
type: "POST",
url: url,
data: { listofIDs: items, personID: personID},
dataType: "json",
traditional: true,
success: function() {
//Rebind grid
}
});
//This listofIDs is ALWAYS null !? (longhand for `$.getJSON` ?)
$.ajax({
url: url,
dataType: 'json',
data: { listofIDs: items, personID: personID },
success: function () {
//Rebind grid
}
});
那么为什么它在顶部工作,但底部总是空的?相同的代码用于构建items
!?
编辑:控制器方法
public ActionResult AddJson(List<int> listofIDs, int personID)
{
if (listofIDs==null || listofIDs.Count < 1)
return Json(false, JsonRequestBehavior.AllowGet);
...
//Add something to database
//Return true if suceeed, false if not
}
编辑所以我最终解决了这个问题,只需将数组转换为字符串并以此方式发送即可。这样我就能发送不仅仅是数组变量。
var items = $(':input:checked').map(function () { return $(this).val();}).toArray();
var stringArray = String(items);
$.ajax({
url: url,
dataType: 'json',
data: { listOfIDs: stringArray, personID: personID },
success: function () {
//rebind grid
}
});
注意不需要设置POST
类型。
答案 0 :(得分:1)
问题可能出在服务器端。在第一种情况下,您在其他HTTP GET中使用HTTP POST。这意味着您可能必须以不同方式访问数据。对于HTTP GET案例,可能需要查看Get individual query parameters from Uri。
答案 1 :(得分:1)
如果没有type: "POST"
,则默认为GET
(according to the docs),您的服务器端代码可能不会预期。
此外,您可以使用...
获取值列表var items = $(':input:checked').map(function() {
return $(this).val();
}).toArray();
不确定它是否更好。我只是一个想法:)
答案 2 :(得分:1)
您没有指定请求的类型,因此默认为GET
。
来自jQuery Docs:
要求的类型(“POST”或“GET”),默认为“GET”。
也许您打算指定POST
。如果您使用GET发送它,则数组将被添加到QUERY_STRING
?listofIDs=...
中,并且无法像通常访问POSTed数据那样访问。