MVC6 Dropdownlist of Countries

The way I make my dropdowns is somewhat similar except that in my ViewModel, my property is of type SelectList instead of an IEnumerable<>.

public class HomeViewModel
{
    public string CountryCode { get; set; }
    public SelectList CountryList { get; set; }
}

Then in the controller I get the data and convert it to an anonymous list with two properties “Id” and “Value”.

In turn, I create a new SelectList() passing in the anonymous list specifying what is the dataValueField and what is the dataTextField.

public IActionResult Index()
{
    var countries = _customersContext.Countries.OrderBy(c => c.CountryName).Select(x => new { Id = x.Code, Value = x.Name });

    var model = new HomeViewModel();
    model.CountryList = new SelectList(countries, "Id", "Value");

    return View(model);
}

Finally, in the View:

<div class="form-group">
    <label asp-for="CountryCode" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <select asp-for="CountryCode" asp-items="@Model.CountryList"></select>
    </div>
</div>

Leave a Comment