如何使用Web Api(MVC)中的Json字符串填充DropDown

时间:2016-03-04 12:09:27

标签: json api asp.net-mvc-4

我正在使用 API 来获取国家/地区列表。

以下链接显示国家/地区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填充View上的DropDown

1 个答案:

答案 0 :(得分: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"))