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 
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Adding [FromBody] was the only thing that worked for me. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.