ASP.NET 无法获得世界上所有国家/地区的完整列表

ASP.NET Cannot get FULL list of ALL countries in the world

世界上有196个国家。

我正在尝试显示一个包含所有选项的下拉列表。

我看到许多开发人员建议使用 CultureInfo 或 ASP.NET,但它缺少一些国家/地区,因为文化和国家/地区是不同的东西。

请问如何获得所有国家/地区的列表?非常感谢你的帮助。

在 ASP.NET 下拉列表中

<asp:DropDownList ID="selCountries" runat="server"></asp:DropDownList>

等同于

<select id="selCountries"></select>

或者,您可以使用 Web 服务通过 JavaScript XMLHttpRequest 对象用国家/地区填充 select 标签。

示例:https://restcountries.eu/

像这样:

(function() {
  var newXHR;

  function sendXHR(options) { // Helper function.
    newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
    if (options.sendJSON === true) {
      options.contentType = "application/json; charset=utf-8";
      options.data = JSON.stringify(options.data);
    } else {
      options.contentType = "application/x-www-form-urlencoded";
    }
    newXHR.open(options.type, options.url, options.async || true);
    newXHR.setRequestHeader("Content-Type", options.contentType);
    newXHR.send((options.type == "POST") ? options.data : null);
    newXHR.onreadystatechange = options.callback;
    return newXHR;
  }

  sendXHR({
    type: "GET",
    url: "https://restcountries.eu/rest/v1/all",
    callback: function() {
      if (newXHR.readyState === 4 && newXHR.status === 200) {
        var data = JSON.parse(newXHR.response);

        var selCountries = document.getElementById("selCountries"); // Get the select tag.

        // You can get the selected country.
        selCountries.onchange = function() {
          alert(this.value);
        };


        var option;

        for (var i = 0; i < data.length; i++) { // For every country make an option tag.
          option = document.createElement("option");
          selCountries.options.add(option, 0);
          selCountries.options[0].value = data[i].name; // Country name from the index «i» of the data array.
          selCountries.options[0].innerText = data[i].name;
          selCountries.appendChild(option); // Append the option tag to the select tag.
        }
      }
    }
  });
})();
<select id="selCountries"></select>

在 ASP.NET MVC5 NET 4.5 中,您可以使用 ViewBag 将对象绑定到 @Html.DropDownList

您需要根据https://restcountries.eu/rest/v1/alljson响应创建模型。

型号:CountryModel.cs

using System.Collections.Generic;

namespace RestCountries.Models
{
    public class Translations
    {
        public string de { get; set; }
        public string es { get; set; }
        public string fr { get; set; }
        public string ja { get; set; }
        public string it { get; set; }
    }

    public class CountryModel
    {
        public string name { get; set; }
        public string capital { get; set; }
        public List<string> altSpellings { get; set; }
        public string relevance { get; set; }
        public string region { get; set; }
        public string subregion { get; set; }
        public Translations translations { get; set; }
        public int population { get; set; }
        public List<object> latlng { get; set; }
        public string demonym { get; set; }
        public double? area { get; set; }
        public double? gini { get; set; }
        public List<string> timezones { get; set; }
        public List<object> borders { get; set; }
        public string nativeName { get; set; }
        public List<string> callingCodes { get; set; }
        public List<string> topLevelDomain { get; set; }
        public string alpha2Code { get; set; }
        public string alpha3Code { get; set; }
        public List<string> currencies { get; set; }
        public List<object> languages { get; set; }
    }
}

控制器:DefaultController.cs

using RestCountries.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace RestCountries.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            string url = "https://restcountries.eu/rest/v1/all";

            // Web Request with the given url.
            WebRequest request = WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;

            WebResponse response = request.GetResponse();

            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);

            string jsonResponse = null;

            // Store the json response into jsonResponse variable.
            jsonResponse = reader.ReadLine();

            if (jsonResponse != null)
            {
                // Deserialize the jsonRespose object to the CountryModel. You're getting a JSON array [].
                List<CountryModel> countryModel = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CountryModel>>(jsonResponse);

                // Set the List Item with the countries.
                IEnumerable<SelectListItem> countries = countryModel.Select(x => new SelectListItem() { Value = x.name, Text = x.name });

                // Create a ViewBag property with the final content.
                ViewBag.Countries = countries;
            }
            return View();
        }
    }
}

查看:Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.DropDownList("Countries")

结果: