Country Drop Down Html Helper for Asp.net MVC

Almost every website or web application need to display countries in the drop down list. If that’s true to your project, the following country drop down html helper for Asp.net MVC may save some time for you.

First, we need all the countries information so that we can put into the select list. Thanks to Mads, we can use the XML countries list. or you can download the countries XML List.

Second, A html helper is created for populating the country data into actual HTML format. Simply put the xml file in the App_Data or any folder that works the best for your application.

public static string CountryDropDown(this HtmlHelper helper, string name, string optionLabel, object selectedValue)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml"));

    StringBuilder b = new StringBuilder();

    b.Append(string.Format("<select name="{0}" id="{0}">", name));
    if (!string.IsNullOrEmpty(optionLabel))
        b.Append(string.Format("<option value="">{0}</option>", optionLabel));

    foreach (XmlNode node in doc.SelectNodes("//country"))
    {
        string selected = string.Empty;
        if (node.Attributes["code"].Value == selectedValue as string)
        {
            selected = "selected="selected"";
        }
        b.Append(string.Format("<option value="{0}" {2}>{1}</option>", node.Attributes["code"].Value, node.InnerText, selected));
    }
    b.Append("</select>");

    return b.ToString();
}

Third,  call the html helper in your View

<%= Html.CountryDropDown("countryCode","Please select", ViewData["countryCode"]) %>

Advertisements