I am trying to return JSON from database table using web api.
Controller
private WebApiEntities dataContext = new WebApiEntities();
[ActionName("GetLocations")]
public IEnumerable<Location> GetLocations()
{
    //IEnumerable<Location> list = null;
    var list = (from c in dataContext.LocationMasters
                select new Location
                {
                    LocationId = c.LocationId,
                    LocationName = c.LocationName
                }).ToList();
    return list.OrderBy(c => c.LocationName);
}
Location Model :
public class Location
{
    public int LocationId { get; set; }
    public string LocationName { get; set; }
    public string LocationImage { get; set; }
}
Can any one help? How to return JSON with parent /node? When I run the above code it displays following output
[
    {
        "LocationId": 5,
        "LocationName": "AMBERNATH",
        "LocationImage": null
    },
    {
        "LocationId": 1,
        "LocationName": "BHIWANDI",
        "LocationImage": null
    },
    {
        "LocationId": 2,
        "LocationName": "KALYAN",
        "LocationImage": null
    },
    {
        "LocationId": 3,
        "LocationName": "THANE",
        "LocationImage": null
    },
    {
        "LocationId": 4,
        "LocationName": "ULHASNAGAR",
        "LocationImage": null
    }
]
                I think what you want is something like this
{
   "locations": [{
        "LocationId": 5,
        "LocationName": "AMBERNATH",
        "LocationImage": null
        },
        {
         "LocationId": 1,
        "LocationName": "BHIWANDI",
        "LocationImage": null
        }]
}
Am I right?
If so the return type of your action cannot be an IEnumerable or array.
What you need to do is return an object with a property containing your array.
public object GetLocations()
{
   //IEnumerable<Location> list = null;
   var list = (from c in dataContext.LocationMasters
            select new Location
            {
                LocationId = c.LocationId,
                LocationName = c.LocationName
            }).ToList();
   return new {location = list.OrderBy(c => c.LocationName) };
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With