1

I am working with API to get list of country.

Following link display JSON of countries :

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

Using following code for access JSON object.

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.

Note: I am calling the API to get the list of countries.And i want to return SelectList here by using Api's response. After that i want to use this SelectList to fill DropDown on View

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Gourav Rana
  • 11
  • 1
  • 6
  • Possible duplicate of [Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON](http://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj) – cokeman19 Mar 04 '16 at 12:20

1 Answers1

2
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..

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")) 
rb4bhushan
  • 115
  • 2
  • 11