ASP.NET无法获取全球所有国家/地区的完整列表

时间:2016-03-15 02:53:21

标签: asp.net cultureinfo country

世界上有196个国家。

我正在尝试显示一个显示所有这些内容的下拉列表。

我看到许多开发人员建议使用ASP.NET的CultureInfo,但它缺少一些国家,因为Culture&国家是不同的东西。

那么我怎么能得到一个符合我目的的所有国家的名单呢?我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

在ASP.NET中使用DropDown

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

相当于

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

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

示例:https://restcountries.eu/

这样的事情:

&#13;
&#13;
(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.
        }
      }
    }
  });
})();
&#13;
<select id="selCountries"></select>
&#13;
&#13;
&#13;

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

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

型号: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")

<强>结果:

enter image description here