asp.net mvc 3 - MVC 3 Razor: Country selection dro

2019-04-02 07:57发布

问题:

My controller action code:

ViewBag.country = from p in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures)
                              select new SelectListItem
                              {
                                  Text = p.EnglishName,
                                  Value = p.DisplayName
                              };

View code:

<dl>
   <dt>
    <label>
        Country:
    </label>
   </dt>
   <dd>
   @Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country)
   </dd>
<dl>

It generates a drop-down list of unsorted languages. But I need a drop-down list of sorted country list. Help Please!!!!

回答1:

Is this what you want?

ViewBag.country = from p in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures).OrderBy(c=>c.Name)
                          select new SelectListItem
                          {
                              Text = p.EnglishName,
                              Value = p.DisplayName
                          };


回答2:

Windows and/or .Net do not contain a list of all countries.

The list of languages/cultures is stable, countries come and go, or change name frequently.

Go to the ISO site, and you can download a list of countries from their site. You have to download this list, and update your data frequently.

Update: The list of country codes is no longer freely distributed by ISO, more information can be found on the iso.org site.

And you have to decide, if you want to include countries like Palestine on this list (Palestine is on this list, just an example of "new" countries). You would probably have to add them manually.