I'm attempting to pass an id (long) plus a list of ids (array) to a controller action. The best luck I've had is getting the id to pass, but I've never gotten the array to post.
I've gone through at least 10 stack overflow articles today trying to get this to work. I'm sure I'm missing something minor, but I'm not sure what.
Javascript & AJAX:
HandleCardReordering: function () {
var ids = new Array();
for (var i = 0; i < $(".CourseSectionId").length; i++) {
ids[i] = $(".CourseSectionId:eq(" + i + ")").val();
}
var courseId = $("#CourseId").val();
$.ajax({
url: "/Content/CourseContent/ReorderCourseSections?courseId=" + courseId + "§ionIds=" + JSON.stringify(ids),
cache: false,
type: "POST",
dataType: 'json',
contentType: "application/json",
traditional: true,
success: function (result) {
//
}
});
},
The ids collection and courseId are valid, I checked them with console.log and they look good.
My Controller method:
[HttpPost]
public async Task<JsonResult> ReorderCourseSections(long courseId, [FromQuery]long[] sectionIds, CancellationToken cancellationToken)
{
return Json(new { success = "true" });
}
I can get courseId to populate via the query string parameter, but sectionIds is always a length 0 array. I tried adding traditional: true, tried to stringify my ids collection, I added [FromQuery] to my sectionIds parameter. None worked. Thanks for looking.
sectionIdsas a string - MVC doesn't know you want that automatically parsed and the default model binder doesn't know how to convert it for you. You have options 1) add a model binder that converts the json to a int array 2) change your parameter to a string (do this in the first instance) and parse it yourself in the action 3) change the format of how you pass your sectionIds (ie not as a JSON string)