I have a jQuery ajax call in which I am trying to send the int IDs of users which can be selected from a table of checkboxes.
I am having a problem with the case that no users are selected. I would expect an empty array but in fact I receive an array of length = 1, containing userId 0 (i.e. an unassigned int value).
The following snippet reproduces the problem
$('#test').click(function () {
var numbers = $('.noElements').map(function () {
// (selector does not match any elements, to demonstrate)
return 1;
}).get();
$.ajax({
url: '/MyController/Test',
type: "GET",
data: { numbers: numbers, count: numbers.length }
});
});
public ActionResult Test(IEnumerable<int> numbers, int count)
{
Assert(numbers.Count() == count);
return null;
}
The Assert fails because numbers
is List<int> { 0 }
. Why is the binding happening like this?
I believe that the default model binder will convert the empty string that is passed to it by the jQuery AJAX call into a integer array that contains a single element containing the default value of an integer (0). Your code would work if you did something like this-
$('#test').click(function () {
var numbers = $('.noElements').map(function () {
return 1;
});
if (numbers.length == 0) {
numbers = null;
count = 0;
}
else count = numbers.length;
$.ajax({
url: '/Home/Test',
type: "GET",
data: { numbers: numbers, count: count }
});
});
See this question for further info and alternate solutions - How to post an empty array (of ints) (jQuery -> MVC 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With