developer developer - 4 months ago 16
C# Question

Bind multiple dropdowns from a single list

In MVC, I have a

which contains CityID, City, StateID, State, CountryID, Country. By using the below code I'm able to get the list of cites:

IEnumerable<SelectListItem> objCityList;
IEnumerable<SelectListItem> objStateList;
IEnumerable<SelectListItem> objCountryList;
using (CityModel objCityModel = new CityModel())
List<CityModel> cityList = objCityModel.getCityList();
objCityList = cityList.AsEnumerable().Select(m => new SelectListItem() {
Text = m.City,
Value = Convert.ToString(m.CityID)

How can I bind distinct State and Country from


From what I understand, you want to extract the State and Country lists from the City list. To do that, you can use something like this

objStateList = cityList.GroupBy(item => item.StateID, (key, items) => new SelectListItem
    Text = items.First().State,
    Value = Convert.ToString(key)
objCountryList = cityList.GroupBy(item => item.CountryID, (key, items) => new SelectListItem
    Text = items.First().Country,
    Value = Convert.ToString(key)