数组发布为空
Array posted as null
我知道这个问题在 SO 中有一些替代方案已经得到解答,但是 none 这些解决方案对我有用。
我有一个整数数组,我想通过 AJAX
POST
到一个方法。但不知何故,控制器中的参数总是 null
。
这是我的 JS
:
function addSelected(cID, pID) {
var id, idList = [];
$("#FilteredCategory_" + pID + "_" + cID + " .content ul li a").each(function () {
id = parseInt(this.className.replace(/[^0-9]/gi, ''), 10);
idList.push(id);
});
$.ajax('@Url.Action("SelectedAdd","Home")', {
type: "POST",
traditional: true,
data: idList,
success: function (data) {
alert(data);
}
});
}
POST
控制器中的方法:
[HttpPost]
public string SelectedAdd(ICollection<int> topicIds)
{
string res = string.Empty;
foreach (var id in topicIds)
{
res += $"Item in list: '{id}' \n ";
}
return res;
}
任何建议,为什么 topicIds
总是 nul
?
您需要传递一个 name/value 对,该对与您的方法中的参数名称相匹配。将 ajax 调用更改为
$.ajax('@Url.Action("SelectedAdd","Home")', {
type: "POST",
traditional: true,
data: { topicIds: idList }, // change
success: function (data) {
alert(data);
}
});
我知道这个问题在 SO 中有一些替代方案已经得到解答,但是 none 这些解决方案对我有用。
我有一个整数数组,我想通过 AJAX
POST
到一个方法。但不知何故,控制器中的参数总是 null
。
这是我的 JS
:
function addSelected(cID, pID) {
var id, idList = [];
$("#FilteredCategory_" + pID + "_" + cID + " .content ul li a").each(function () {
id = parseInt(this.className.replace(/[^0-9]/gi, ''), 10);
idList.push(id);
});
$.ajax('@Url.Action("SelectedAdd","Home")', {
type: "POST",
traditional: true,
data: idList,
success: function (data) {
alert(data);
}
});
}
POST
控制器中的方法:
[HttpPost]
public string SelectedAdd(ICollection<int> topicIds)
{
string res = string.Empty;
foreach (var id in topicIds)
{
res += $"Item in list: '{id}' \n ";
}
return res;
}
任何建议,为什么 topicIds
总是 nul
?
您需要传递一个 name/value 对,该对与您的方法中的参数名称相匹配。将 ajax 调用更改为
$.ajax('@Url.Action("SelectedAdd","Home")', {
type: "POST",
traditional: true,
data: { topicIds: idList }, // change
success: function (data) {
alert(data);
}
});