I'm trying to post json objects to MVC in visual studio 2015 preview. However, the data doesn't seem to bind to the action methods parameter. There used to be a JsonValueProviderFactory registered in previous versions of MVC that handled this but I cannot seem to find it in MVC6? Has the setup changed, this used to work out-of-the box in previous versions?
Basically I have a controller method
public ActionResult Save(Person person)
{
...
}
Which I'm trying to call from javascript:
var personData = { Name : 'John Doe' };
$.ajax({
url: '@Url.Content("~/Person/Save")',
type: "POST",
data: JSON.stringify(personData ),
dataType: "json",
contentType: "application/json; charset=utf-8"
})
In previous versions of MVC, the json object was mapped to the c# parameter, see this article for example http://webcognoscere.com/post/How-to-POST-a-JSON-object-to-a-Controller-Action.aspx
Add [FromBody]
to the parameter. In MVC 6 the logic from MVC and Web API was merged into one system. This means that contents that need to be deserialized as JSON from the body of a post need to explicitly noted in the action method's parameter:
public ActionResult Save([FromBody] Person person)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With