Tuesday, 2 October 2012

Country List for ASP.NET MVC

A Common problem in code is creating country lists for forms in web applications.  To avoid keeping your own lists internally or refreshing the countries all the time simply use the .NET Framework culture info to get your list for you :-) As Below:

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>


 

 

4 comments:

  1. Thank you very much! Very smart.

    ReplyDelete
  2. Excellent. Saved me from retying the list. Very clever.

    ReplyDelete
  3. Just in case someone wants a default country selected you can replace the line:

    countryNames.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") });

    ReplyDelete