2016-03-04 42 views
1

我正在與API獲取國家列表。如何使用JSON字符串從Web Api(MVC)填充DropDown

下列國家的鏈接顯示JSON

http://ws.postcoder.com/pcw/PCW45-12345-12345-1234X/country?format=json

使用下列訪問JSON對象代碼。

System.Net.WebClient wc = new System.Net.WebClient(); 
var response = wc.DownloadString("http://ws.postcoder.com/pcw/PCW45-12345-12345-1234X/country?format=json"); 

但我有一些訪問它的問題。我想用這個response變量填充這些國家的DropDown

注意:我打電話給API來獲取國家列表。我想通過使用Api的響應返回SelectList。從那以後,我想用這個的SelectList來填充下拉上查看

+0

[使用JSON結果填充下拉列表的可能重複 - 使用MVC3,JQuery,Ajax,JSON的Cascading DropDown](http://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using- MV C3-的jquery-AJ) – cokeman19

回答

1
var jsonResponse = System.Net.WebClient.wc.DownloadString("YourApiUrl"); // you need to parse your json 
dynamic Data = Json.Decode(jsonResponse); 

假設您的API結果就像{"Id":"101","Name":"Ravi Bhushan"},{"Id":"102","Name":"Abcd"}等。

List<SelectListItem> List = new List<SelectListItem>(); 

foreach (var x in Data) { 
    List.Add (new SelectListItem() { 
     Text = x.Name, 
     Value = x.Id 
    });    
} 
return List;// return list to view then bind your ddl with.. 

現在你可以綁定你的下拉像

@Html.DropDownList("yourDropdown", Model.List) // examples 

@Html.DropDownListFor(M => M.yourDropdown, new SelectList(Model.List,"Value", "Text"))