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 plex object?
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 plex object?
- You can skip the stringify by using [FromBody] in the header. see stackoverflow./questions/27869763/… – Peter Kellner Commented Jan 9, 2015 at 23:44
3 Answers
Reset to default 8You don't need to wrap your data into model
property:
var data = { ID: 1 };
$http.post('/api/MyResource/MyPostAction', data);
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.
$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);