peter
peter

Reputation: 2103

POST a list of objects to MVC 5 Controller

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?

Upvotes: 4

Views: 3711

Answers (1)

Starscream1984
Starscream1984

Reputation: 3062

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 
}

Upvotes: 4

Related Questions