Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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().
like image 346
Matthijs Wessels Avatar asked Jul 20 '11 09:07

Matthijs Wessels


1 Answers

You could do this:

var myIntArray = new Array();

// add elements or leave empty
myIntArray.push(1);
myIntArray.push(5);

var data = myIntArray.length > 0 ? { myIntArray: myIntArray } : null;

$.ajax({
    url: '@Url.Action("someAction")',
    type: 'POST',
    data: data,
    traditional: true,
    success: function (result) {
        console.log(result);
    }
});

or use a JSON request:

var myIntArray = new Array();
// add elements or leave empty
myIntArray.push(1);
myIntArray.push(5);

$.ajax({
    url: '@Url.Action("someAction")',
    type: 'POST',
    data: JSON.stringify(myIntArray),
    contentType: 'application/json',
    success: function (result) {
        console.log(result);
    }
});
like image 165
Darin Dimitrov Avatar answered Nov 09 '22 08:11

Darin Dimitrov