Roj Beraña Roj Beraña - 2 months ago 9
AngularJS Question

angularjs resource pass an array of object parameter but is null in api controller

I have an angularjs resource as seen below:

return $resource('/api/report',
{ },
{
save: { method: 'POST', url: '/api/fileupload/savefile', isArray: false },
});


My angularjs controller that uses this resource is below:

$scope.save = function () {
var reportFieldsSample = [{ Field: 'ff', Value: 'gg' }, { Field: 'aa', Value: 'dd' }];
Report.save({ reportParams: reportFieldsSample},
{ },
function (content) {
console.log(content);
});


My WebApiConfig for this route is:

config.Routes.MapHttpRoute(
"SaveFile",
"api/fileupload/savefile",
new { controller = "FileUpload", action = "SaveFile" },
new { httpMethod = new HttpMethodConstraint("POST") });


My mvc api controller that receives this is below:

[HttpPost]
public HttpResponseMessage SaveFile(IList<Parameter> reportParams)
{
//reportParams is null
}


Parameter class is declared in this way:

public class Parameter
{
public string Field { get; set; }
public string Value { get; set; }
}


The request enters my api controller but the
reportParams
argument of the controller is always null.
Can you help me point out the problem? Thanks

Answer

The reason that you are getting null in you web api controller is because the structure you are sending from client is not matching the server parameter declaration.

What you can do on the server side is to declare object such as

class ReportParamsModel {
  public IList<Parameters> reportParams {get; set;}
}

You controller method becomes

public HttpResponseMessage SaveFile(ReportParamsModel params)

and you are set to go

You can also use the dynamic support in webapi, where the controller method becomes

public HttpResponseMessage SaveFile(dynamic data) {
    //data.reportParams contains you array (but each object again is a dynamic object.
}