MVC with jQuery Ajax call incorrectly binds empty array / enumerated

I have a jQuery ajax call in which I am trying to send int identifiers to users that can be selected from a checkbox table.

I have a problem with no users being selected. I would expect an empty array, but in fact I get an array length = 1 containing userId 0 (i.e. the 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; } 

Assert error because numbers is List<int> { 0 } . Why is binding so?

+7
source share
1 answer

I believe that the middleware will by default convert the empty string passed to it by jQuery AJAX call into an integer array containing one element containing the default value of the integer (0). Your code will 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 more information and alternative solutions - How to send an empty array (from ints) (jQuery -> MVC 3)

+1
source

All Articles