Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post JSON data in MVC Visual Studio 2015

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

like image 310
Bjorn Avatar asked Jan 09 '23 09:01

Bjorn


1 Answers

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)
{
    ...
}
like image 115
Eilon Avatar answered Jan 14 '23 17:01

Eilon