3

I have a class like below for posting to asp.net web api

public class PostData
{

    public int ID { get; set; }

    public int[] SelectedChoiceIDs { get; set; }

}

In my ApiController there is a method called send which gets PostData object as parameter.

public bool Send(PostData data)
{


}

The problem is whenever I trace the method Web API is not binding to the array of integers ,that is, SelectedChoiceIDs property. How can i force to bind the array of integers to "SelectedChoiceIDs" property?

The data i'm sending is like

{ "ID" : 3 , "SelectedChoiceIDs" : [ 3,4,5,6 ] } 
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
kkocabiyik
  • 4,246
  • 7
  • 30
  • 40

2 Answers2

9

You don't need to do anything, this will work out of the box.

If you POST the exact object you provided:

{ "ID" : 3 , "SelectedChoiceIDs" : [ 3,4,5,6 ] } 

with Content-Type: application/json, the default model binder will automatically pick it up.

public class PostData
{

    public int ID { get; set; }

    public int[] SelectedChoiceIDs { get; set; }

}

public void DummyController : ApiController
{
    public void Post(PostData data)
    {
        //data here will be PostData with ID and an array of 4 integers
    }
}

Make sure you provide the Content-Type, and that you are indeed posting correct JSON, not for example:

{data: { "ID" : 3 , "SelectedChoiceIDs" : [ 3,4,5,6 ] } }
Filip W
  • 27,097
  • 6
  • 95
  • 82
-3

Possible dupplicate of ASP.NET MVC bind array in model

Here is blogpost explaining what you have to do.

Community
  • 1
  • 1
semao
  • 1,757
  • 12
  • 12