developer
developer

Reputation: 25

Bind multiple dropdowns from a single list

In MVC, I have a List<CityModel> 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 cityList?

Upvotes: 1

Views: 340

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205619

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)
});

Upvotes: 0

ChrisF
ChrisF

Reputation: 137148

You just need to use the one list, but change the which property is displayed in the combobox. The selected item is of the same type as the objects on the list.

In your view model just expose the CityList property and then bind the comboboxes ItemsSource to that property.

You can do all this in XAML for instance, like this:

<ComboBox ItemsSource="{Binding CityList}"
         DisplayMemberPath="City"
         SelectedItem={Binding SelectedCity, Mode=TwoWay>
</ComboBox>

<ComboBox ItemsSource="{Binding CityList}"
         DisplayMemberPath="County"
         SelectedItem={Binding SelectedCounty, Mode=TwoWay>
</ComboBox>

<ComboBox ItemsSource="{Binding CityList}"
         DisplayMemberPath="State"
         SelectedItem={Binding SelectedState, Mode=TwoWay>
</ComboBox>

Upvotes: 0

Related Questions