Tony
Tony

Reputation: 12715

MVC WebAPI + Angular post = every param is null on the server side

I have the following class:

public class SomeArg
{
     public int name { get; set; }
}

the POST request sends that data

var requestData = {};
requestData.items = [{ name: 1 }, { name: 2 }];
requestData.logic = "and";

 $http.post('SomeAction/',
            JSON.stringify(requestData),
            { headers: { 'Content-Type': 'application/json' } }
           )
           .success(function (data, status, headers, config) {
           }).
           error(function (data, status, headers, config) {
           });

and the WebApi controller's action

[HttPost]
public HttpResponseMessage SomeAction(string logic = null,
        [FromUri]
        SomeArg[] items = null) { ... }

I can see that all of the arguments are null. Why ?

Upvotes: 1

Views: 1210

Answers (1)

Chandermani
Chandermani

Reputation: 42669

The API controller POST method should look like this

[HttPost]
public HttpResponseMessage SomeAction(string logic = null,
        [FromBody]SomeArg[] items = null) { ... }

And the angular call should not serialize the object. Angular will do it.

$http.post('SomeAction/',
            requestData,
            { headers: { 'Content-Type': 'application/json' } }
           )
           .success(function (data, status, headers, config) {
           }).
           error(function (data, status, headers, config) {
           });

Update: I rechecked item passed to server, i think you should create a single object on the server that encapsulates the data being passed in POST such as

public class ActionData {
  public string logic {get;set;}
  public SomeArg[] items {get;set;}
}

and use this as a single argument to your Web API function

public HttpResponseMessage SomeAction(ActionData data) { ... }

Please read how parameter binding works in webapi http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Upvotes: 3

Related Questions