Reputation: 9940
I want to send an array as a JSON string in the request body using HTTP POST:
{
{
A: 0,
B: 1
},
{
A: 2,
B: 3
}
}
I have the following data structure:
public class Test
{
[Display(Name = "A")]
[Range(1, 2147483647)]
[Required]
public int A { get; set; }
[Display(Name = "B")]
[Range(0, 2147483647)]
[Required]
public int B { get; set; }
}
And this is my action:
[HttpPost]
[ResponseType(typeof(WriteResponse))]
[Route("Account/{clientId:int}/Test")]
public IHttpActionResult PostEventTest(int clientId, [FromBody]Test[] test){}
When I hit this action, the test param is null. How can I receive an array of a certain type through the request body?
Upvotes: 1
Views: 9492
Reputation: 21128
If Test should represent the whole JSON, then it is wrong. Even your complete JSON is wrong, because it is not an array. Correct JSON would be:
{
"list": [
{
"A": "0",
"B": "1"
},
{
"A": "2",
"B": "3"
}
]
}
Or something like this:
{
"item1": {
A: 0,
B: 1
},
"Item2": {
A: 2,
B: 3
}
}
For this, you model has to change to. For the first example your model should look like:
public class TestModel
{
public IList<Test> list
{ get; set; }
}
public class Test
{
[Display(Name = "A")]
[Range(1, 2147483647)]
[Required]
public int A { get; set; }
[Display(Name = "B")]
[Range(0, 2147483647)]
[Required]
public int B { get; set; }
}
For the second example the Test
class would be the same, only TestModel
would change:
public class TestModel
{
public Test item1
{ get; set; }
public Test item2
{ get; set; }
}
But only the first example is an array. To test whether your JSON is correct, use jsonlint
EDIT
With my example, you don't need the [FromBody]
part, because you can pass TestModel
as a parameter of your method. Which is in my point of view even nicer.
Upvotes: 2
Reputation: 2380
What you are sending is not an array. It should go something like:
{"test":[
{"A":"0", "B":"0"},
{"A":"0", "B":"1"},
{"A":"1","B":"1"}
]}
See more here (w3schools).
Upvotes: 2