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?

1

3 Answers 3

8

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

var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);
Sign up to request clarification or add additional context in comments.

1 Comment

I was missing public on my property... This helped though. Thanks.
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.

Comments

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);

5 Comments

That didn't work. :/ (I took out the header config object and I took out the JSON.stringify)
Oh I've used the Package Manager to get Ninject and Newtonsoft's JSON.NET. Maybe that's interfering somehow?
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.
@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
I was missing public on my property. Thanks for all the help though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.