2016-05-17 4 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

ありがとうございます。 –

関連する問題