2

I tried to follow this example.

Here is my C# code:

public class MyModel
{
    int? ID { get; set; }
}

public class MyResourceController : ApiController
{
    [HttpPost]
    public MyModel MyPostAction(MyModel model)
    {
        return model;
    }
}

Here is my JavaScript:

var data = { model: { ID: 1 } };
$http.post(
    '/api/MyResource/MyPostAction',
    JSON.stringify(data),
    {
        headers: {
            'Content-Type': 'application/json'
        }
    }
);

When I set a breakpoint in my action and model.ID is null instead of 1. How can I POST a complex object?

Community
  • 1
  • 1
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
  • You can skip the stringify by using [FromBody] in the header. see http://stackoverflow.com/questions/27869763/how-to-post-an-object-to-webapi-using-angularjs/27869884#27869884 – Peter Kellner Jan 09 '15 at 23:44

3 Answers3

8

You don't need to wrap your data into model property:

var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);
cuongle
  • 74,024
  • 28
  • 151
  • 206
3

Adding public to the property on MyModel fixed it (facepalm).

I ended up using this on the client:

var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);

Thanks everyone.

Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
2
$http.post('/api/MyResource/MyPostAction', data);

Remove the JSON.stringify and post the data as is.

You don't need to specify json header either as it is the default for post.

On the server:

Remove Xml from webapi if you're only using json

//WebApiConfig.js
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
James Kyburz
  • 13,775
  • 1
  • 32
  • 33
  • That didn't work. :/ (I took out the header config object and I took out the JSON.stringify) – Jesus is Lord Aug 06 '13 at 14:22
  • Oh I've used the Package Manager to get Ninject and Newtonsoft's JSON.NET. Maybe that's interfering somehow? – Jesus is Lord Aug 06 '13 at 14:23
  • JSON is only the default if data is supplied and not undefined. Otherwise it is XML. This is important if you don't have a media formatter for XML for your Web API controller. – Steve Klösters Aug 06 '13 at 14:24
  • @WordsLikeJared Strange. Have updated the answer to remove the xml formatter from the webapi, although it shouldn't be that stupid to try xml when the http header states json – James Kyburz Aug 06 '13 at 14:32
  • I was missing `public` on my property. Thanks for all the help though. – Jesus is Lord Aug 06 '13 at 14:36