Yes, I know there is a gazillion posts about sending array data using angular $esource. I read this, this, and pretty much the top 10 google results on this topic, but I still can't make it work. I suspect that it might have to do with the server side API, but I am really not sure.
Please help me figure this out. I am trying to POST an array of data to the .NET API using angular $resource.
$Resouce:
ResourceModule.service('PartProgramsResource', function ($resource) {
var url = _baseUrl + '/parts/:partId/programs'
return $resource(url, { partId: '@partId' }, {
add: {method: 'POST', isArray: true}
});
})
Inside controller:
app.controller("EditPartCtrl", function ($scope, PartProgramsResource){
$scope.save = function(){
var programsToSave = ["program 1", "program2"];
var resource = new PartProgramsResource(programsToSave);
resource.$add({ partId: $scope.part.id });
}
}
Debugger:
I hope I am not mistaking this, but it seems to me that my array turns into an object?? with array index as the key? or this is how array looks like in the request payload?
.NET API:
[HttpPost]
[Route("{partId:int:min(1)}/programs"
, Name = ApplicationApiRoutes.Parts.AddPartPrograms)]
[ResponseType(typeof(IEnumerable<KeyValueOutput>))]
public HttpResponseMessage AddPartPrograms([FromUri] int partId, [FromBody] List<string> programNames)
{
return Execute(() => _partFacade.AddPartPrograms(partId, programNames.ToArray(), CurrentUser));
}
Calling the API with the above resource will cause an System.NullReferenceException error. The programNames parameter is null.
When I went through the stackoverflow posts regarding this topic, I mostly see this syntax being used:
var resource = new PartProgramsResource();
resource.$add({ partId: $scope.part.id }, programsToSave);
However, this never works for me and the request payload will be an empty object.
Any help will be appreciated since I am absolutely, terribly stuck....
You can modify data using transformRequest
Am not 100% sure why angular does this, but i think it expects object to be passed. so if you have send data like {myArray: [...]} this will be ok.