I am passing a List of IDs to a controller method in my .NET MVC project with an Ajax call.
But sometimes there are no IDs to pass and so I want to either pass an empty list or null.
However instead of an empty list or null it passes a List with a single ID of 0.
Here is my controller method:
public ActionResult MultipleDaysModal(List<int> IDs)
{
if (IDs.Any())
{
ViewBag.CurrentDays = ReservationHelper.GetBlockoutsByIDs(IDs)
.OrderBy(i => i.BlockoutTime1)
.ToList();
}
return View("ReservationPartials/_MultipleDaysModal");
}
Below is my first attempt at the Ajax method:
function loadMultipleDays() {
var blockoutIDString = $('#blockoutIDs').val();
// had to split, otherwise the controller didn't recognize it as a list of ints
var blockoutIDs = blockoutIDString.split(',');
$.ajax({
url: '@Url.Action("MultipleDaysModal", "Reservations")',
method: 'GET',
traditional: true,
data: { 'IDs': blockoutIDs },
success: function (data) {
// Do stuff
},
error: function (xhr) {
// DO stuff
}
});
}
When I got the problem of the non-empty list I tried to force it to be null:
function loadMultipleDays() {
var blockoutIDString = $('#blockoutIDs').val();
// had to split, otherwise the controller didn't recognize it as a list of ints
var blockoutIDs = blockoutIDString ? blockoutIDString.split(',') : null;
// Ajax call . . .
}
However I still got the same List with a single ID of 0. This bypasses my check of IDs.Any(). I know I can change the if statement to check differently, however I would like to understand why this is happening.
Edit: When I step through the javascript in devtools the variable blockoutIDs
is in fact set to null (since I currently have the second attempt running). When looking at the request the query string parameters shows 'IDs=' and as JSON 'IDs:' so nothing.