Roj Beraña Roj Beraña - 1 year ago 85
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:

$ = function () {
var reportFieldsSample = [{ Field: 'ff', Value: 'gg' }, { Field: 'aa', Value: 'dd' }];{ reportParams: reportFieldsSample},
{ },
function (content) {

My WebApiConfig for this route is:

new { controller = "FileUpload", action = "SaveFile" },
new { httpMethod = new HttpMethodConstraint("POST") });

My mvc api controller that receives this is below:

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
argument of the controller is always null.
Can you help me point out the problem? Thanks

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download