1

I have an end-point in ASP.NET WEB API application which looks like this:

        [HttpPost]
        public dynamic Save(string userId, List<MyObject> data)
        {
            return null;
        }

public class MyObject
    {
        public string name { get; set; }
        public List<itemAttribute> items { get; set; }
    }

public class itemAttribute
    {
        public int id { get; set; }
        public string typeName { get; set; }
        public string fullName { get; set; }
        public bool Checked { get; set; }
    }

I am trying to post following JavaScript object

data = [
{
    "name": "One",
    "items": [
        {
            "fullName": "name",
            "Checked": true,
            "typeName": "type 1",
            "id": 1
        },
        {
            "fullName": "nametwo",
            "Checked": true,
            "typeName": "some type 2",
            "id": 2
        }
    ]
}
    ]

When the I hit the endpoint, data is coming as an empty list. I don't see any specific error. Please help.

Right now I am posting data using REST Client of fire fox

enter image description here

SharpCoder
  • 18,279
  • 43
  • 153
  • 249

2 Answers2

1

You shouldn't try to pass multiple parameters. Change the signature to this:

public dynamic Save([FromBody] List<MyObject> data)

Also, try to stringify your object before passing it to the Web API:

JSON.stringify(data);
nunob
  • 592
  • 7
  • 24
  • Thank you for quick help. I should be able to send multiple parameters. I have used multiple parameters earlier as well. I have tried making use of your suggestion(sending single parameter & using FromBody attribute) but its not helping. – SharpCoder Nov 18 '14 at 14:22
  • Passing multiple parameters using Web API is not supported on POST methods, or at least is nothing that comes out-of-the-box and requires some workarounds. I don't have access to your code but try to change the List to be a simple array MyObject[] or look into the [ModelBinder]. Did you also stringify the data object? – nunob Nov 18 '14 at 14:44
1

you have to change two things to get this working:
1st: Change your post method signature to:

[HttpPost]
public dynamic Save(string userId, [FromBody]List<MyObject> data) {

2nd: Remove the data = from your json. It should look like:

[
{
    "name": "One",
    "items": [
        {
            "fullName": "name",
            "Checked": true,
            "typeName": "type 1",
            "id": 1
        },
        {
            "fullName": "nametwo",
            "Checked": true,
            "typeName": "some type 2",
            "id": 2
        }
    ]
}
]

The data = confuses the modelbinder and your list is null.

Stefan Ossendorf
  • 696
  • 6
  • 14