Country List for ASP.NET MVC
Step 1 - Add a method to your service layer
public IEnumerable<SelectListItem> GetCountries(){
RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);
List<SelectListItem> countryNames = new List<SelectListItem>();
//To get the Country Names from the CultureInfo installed in windows
foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);
countryNames.Add(new SelectListItem() { Text = country.DisplayName, Value = country.DisplayName });
}
//Assigning all Country names to IEnumerable
IEnumerable<SelectListItem> nameAdded = countryNames.GroupBy(x => x.Text).Select(x => x.FirstOrDefault()).ToList<SelectListItem>().OrderBy(x => x.Text);
return nameAdded;
}
Step 2 - Add a call in your controller to populate a view bag
ViewBag.CountryList = GetCountries();Step 3 - Bind your html drop down list and model in your view
<td>@Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.CountryList)
</td>
Thank you very much! Very smart.
ReplyDeleteThank You very much. Nice
ReplyDeleteExcellent. Saved me from retying the list. Very clever.
ReplyDeleteJust in case someone wants a default country selected you can replace the line:
ReplyDeletecountryNames.Add(new SelectListItem() { Text = country.DisplayName, Value = country.DisplayName });
by a line like:
countryNames.Add(new SelectListItem() { Text = country.DisplayName, Value = country.DisplayName, Selected = (country.DisplayName == "United States") });