4

I would like to post a list of objects to an MVC 5 Controller but only NULL reaches the Controller method. This POST:

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "../delikte",
    data: JSON.stringify({ "delikte" : delikte})
});

goes to this MVC 5 Controller:

[HttpPost]
[Route(@"delikte")]
public void saveDelikte(List<Delikt> delikte)
{
  ... // delikte is null 
}

As I can see from IE debug tools, the POST contains the following data:

{"delikte":[{"VerfahrenId":"6","DeliktId":"4123"},{"VerfahrenId":"6","DeliktId":"4121"}]} 

And should be converted to a List of this object:

public class Delikt
{
    public int VerfahrenId { get; set; }
    public int DeliktId { get; set; }
}

I thought it could be a problem from the definition of VerfahrenId and DeliktId as int in the class Delikt, but changing to string did not change the problem.

I have read other threads but I could not find a solution there (my post includes dataType, contentType, the posted information seems in the right format). Where is my mistake?

1 Answer 1

4

I would try removing the property name from your POST data:

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "../delikte",
    data: JSON.stringify(delikte)
});

It may also help to explicitly specify that the value comes from the POST body:

[HttpPost]
[Route(@"delikte")]
public void saveDelikte([FromBody]List<Delikt> delikte)
{
    ... // delikte is null 
}
3
  • Removing the property name from the POST data worked, thank you very much. I had not seen this in any of the examples I have searched.
    – peter
    Commented Jul 9, 2015 at 8:18
  • No problem, I had similar issues when I started working with Web API a couple of years ago. If you could mark the answer as accepted that would be great, thanks. Commented Jul 9, 2015 at 8:22
  • Adding [FromBody] was the only thing that worked for me. Thank you.
    – David
    Commented May 4, 2018 at 11:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.