How to post an empty array (of ints) (jQuery -> MVC 3)

Viewed 4191

Using jQuery I am posting an array of int to my MVC 3 application by putting the array in the data parameter like so: data: { myIntArray: myIntArray }. In my controller, the receiving action has as a parameter int[] myIntArray.

This goes well in most cases, except when myIntArray is empty. In the request I see the following myIntArray= (note that there is no space after "="). Back in my MVC 3 controller this gets translated to an array containing one int: 0.

It doesn't seem to me like I am doing something terribly wrong here by posting an empty array. I can work around this by handling the case where the array is empty in a different way. Nevertheless, I feel that this should be possible.

Thanks in advance.

Extra info:

  • I use jQuery 1.5.1 (cannot upgrade for this project).
  • myIntArray is initialized with new Array().
2 Answers

Just in case anyone lands on this question trying to resolve this...

This is a bug in MVC (that still exists in MVC 4 in 2019, duh):

  • when you POST an empty form parameter into an action method that has an array-mapped variable or model - this results in an 1-element zero array { 0 }.

I found no other way than to deal with it on the back-end.

Here's another question discussing it: ASP.NET MVC Int Array parameter with empty array defaults to {0}

Related