1

I merge two arrays in my AngularJS controller and sent it via http.post:

var selectedIds = angular.extend({}, $scope.selectedFirstKeys, $scope.selectedSecondKeys);
            $http.post("/api/tests/test/1", selectedIds )
                .then(function (response) {
                    ...                    
            });

With Fiddler I see the array is sent like this:

{"0":22}

But when I define my POST method like this it doesn't recognize the array:

[HttpPost("test/{testId:long}")]
    public IActionResult Test(long testId, [FromBody] long[] selectedIds)
    {
        ...
    }

How do I define the Controller method so it recognizes the array?

Palmi
  • 2,381
  • 5
  • 28
  • 65
  • `{"0":22}` isn't really an array, it an object. Arrays are in square brackets `[0,22,...]`. Are you sure that what you are passing is correct? – R. Richards Mar 10 '17 at 18:55
  • That is what the angular.extend method created for me. And the data is correct. An array with one item (22) – Palmi Mar 10 '17 at 18:57
  • Are `$scope.selectedFirstKeys` and `$scope.selectedSecondKeys` arrays? – lealceldeiro Mar 10 '17 at 18:58

1 Answers1

0

Taking into consideration that what you want to pass to your backend logic is an array.

This code is wrong

var selectedIds = angular.extend({}, $scope.selectedFirstKeys, $scope.selectedSecondKeys);
  • Because: it copies the content of $scope.selectedFirstKeys, and $scope.selectedSecondKeys into {} (which is an object!), so the final result will be an object too! :(

The correct way (Assuming that $scope.selectedSecondKeys and $scope.selectedSecondKeys are arrays) is:

$scope.selectedFirstKeys = $scope.selectedFirstKeys.concat($scope.selectedSecondKeys);
  • Because: it set $scope.selectedFirstKeys with the result of cancatenating $scope.selectedFirstKeys and $scope.selectedSecondKeys, which will be an array too! :)

You might want to see additional info about Array.prototype.concat (and on SO) and angular.extend (and on SO). An extract is shown below:


Array.prototype.concat

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

Syntax

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

Parameters

valueN: Arrays and/or values to concatenate into a new array.


angular.extend

Extends the destination object dst by copying own enumerable properties from the src object(s) to dst.

Syntax

angular.extend(dst, src);

Parameters

dst: Destination object

src: Source object(s)

Community
  • 1
  • 1
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80