2016-05-17 32 views
1

我想從數據庫表中使用web api返回JSON。在web api中使用父/根節點返回json

控制器

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); 
} 

選址模型:

public class Location 
{ 
    public int LocationId { get; set; } 
    public string LocationName { get; set; } 
    public string LocationImage { get; set; } 
} 

任何一個可以幫助?如何用父/節點返回JSON?當我運行上面的代碼會顯示以下輸出

[ 
    { 
     "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 
    } 
] 
+0

你的問題是什麼? –

+0

從哪裏調用此API? –

+0

@CuongLe我想父節點在Json之前。有什麼辦法來達到這個目的? –

回答

0

我想你想要的是像這樣

{ 
    "locations": [{ 
     "LocationId": 5, 
     "LocationName": "AMBERNATH", 
     "LocationImage": null 
     }, 
     { 
     "LocationId": 1, 
     "LocationName": "BHIWANDI", 
     "LocationImage": null 
     }] 
} 

我說得對不對?

如果是這樣,您的操作的返回類型不能是IEnumerable或數組。

你需要做的是返回一個包含你的數組的屬性的對象。

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) }; 
} 
+0

謝謝..它正在工作 –