[英]How to populate DropDown using Json string from Web Api (MVC)
I am working with API to get list of country. 我正在使用API来获取国家/地区列表。
Following link display JSON
of countries : 以下链接显示国家/地区的
JSON
:
http://ws.postcoder.com/pcw/PCW45-12345-12345-1234X/country?format=json http://ws.postcoder.com/pcw/PCW45-12345-12345-1234X/country?format=json
Using following code for access JSON object. 使用以下代码访问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");
But I have some issues for accessing it. 但是我在访问它时遇到了一些问题。 I want to use this
response
variable to populate DropDown
form these countries. 我想使用此
response
变量在这些国家/地区填充DropDown
。
Note: I am calling the API to get the list of countries.And i want to return SelectList here by using Api's response. 注意:我正在调用API以获取国家/地区列表,并且我想通过使用Api的响应在此处返回SelectList。 After that i want to use this SelectList to fill DropDown on View
之后,我想使用此SelectList填充View上的DropDown
var jsonResponse = System.Net.WebClient.wc.DownloadString("YourApiUrl"); // you need to parse your json
dynamic Data = Json.Decode(jsonResponse);
Suppose your api result is like {"Id":"101","Name":"Ravi Bhushan"},{"Id":"102","Name":"Abcd"}
etc.. 假设您的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..
Now you can bind your dropdown like 现在,您可以像这样绑定下拉列表
@Html.DropDownList("yourDropdown", Model.List) // examples
@Html.DropDownListFor(M => M.yourDropdown, new SelectList(Model.List,"Value", "Text"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.