I know that this question has some alternatives in SO that have been answered, but none of these solutions worked for me.
I have an array of integers that I want to POST
to a method via AJAX
. But somehow the parameter is always null
in the controller.
Here is my 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
method in controller:
[HttpPost]
public string SelectedAdd(ICollection<int> topicIds)
{
string res = string.Empty;
foreach (var id in topicIds)
{
res += $"Item in list: '{id}'
";
}
return res;
}
Any suggestions, why topicIds
is always nul
?
You need to pass a name/value pair which matched the name of the parameter in your method. Change the ajax call to
$.ajax('@Url.Action("SelectedAdd","Home")', {
type: "POST",
traditional: true,
data: { topicIds: idList }, // change
success: function (data) {
alert(data);
}
});