MVC Rest API - Unable to get Collection in json parameter
Asked Answered
A

0

0

I'm trying to send this json to my controller

{  
   "Name":"Ford Focus",
   "CarProperties":[  
      {
         "Name":"Airbag"
      }
   ]
}

As you see there is a Collection named as CarProperties. I want to handle this collection in my Controller function. But getting null.

Controller

public class TestController : ApiController
{

    public CarViewModel PostCar(CarViewModel car)
    {
        //Here is the error
        // Output is : {"Name":"Ford Focus"} so, car.CarProperties has come as null
        return car;
    }

}

View Models

public class CarPropertyViewModel {
    public string Name;
}

public class CarViewModel
{
    public string Name;
    public List<CarPropertyViewModel> CarProperties { get; set; }
}

What I am doing wrong?

Ahoy answered 11/11, 2016 at 10:7 Comment(4)
You just passing an object, not a collection. It would need to be CarProperties: [{ "CarPropertyID":1, "Name":"Airbag" }] in order to bind to a collection. Alternatively, change the model to ` public CarPropertyViewModel CarProperties { get; set; }` and make Name a property as well (fields are not bound)Hyonhyoscine
@StephenMuecke The json that you see was incorrect, I have changed the json and modified the code as you said (Please see updated post), but result is still the same, what do you think?Ahoy
and make Name a property as well (fields are not bound)Hyonhyoscine
There's a bunch of different ways to do web services with .NET, you can use WCF, MVC, Web API, straight ASP.NET.. depending on which way you're doing it, there are configuration and annotation details that affect how .NET is expecting your json to be formed. And jquery's ajax settings affect the way your json ends up getting formed. It's a bit of a hairy ball. Anyway, to solve your issue, we need to see the ajax call, the web.config, the controller and method annotations, what usings your using.. etc.Hazelwood

© 2022 - 2024 — McMap. All rights reserved.