Reputation: 181
@foreach (var item in Model) { string mytown = item.town.*enter distinct here* <option value="@mytown"> @mytown</option>
This selects all the town names in my database and I've got it to display in a drop down menu.
How can I change this so that when it's displaying the town names, it will only show each town name once.
For example, if I have 3 londons in the database it will show all 3 londons in the drop down menu. I want it to only show 1 london
FYI: Sorry this may seem like a repost but I posted the wrong code earlier
Upvotes: 1
Views: 8421
Reputation: 5186
As far as my understanding, you can't do this if you are using ID as value.
Say
ID | Value
1 Landon
2 Landon
3 Landon
4 Los Angeles
Better way you can achieve this is by using LINQ. Get the list from the database then filter it in the controller towns.Where(x => x.Name == x.Name.Distinct());
further Inside controller action
ViewBag.towns = new SelectList(towns.Where(x => x.Name == x.Name.Distinct()).ToList(), "Value", "Text");
Inside view
@Html.DropDownListFor(x => x.SelectedTown, new SelectList(ViewBag.towns, "ID", "Name", Model.SelectedTown))
Upvotes: 1
Reputation: 25705
Why not convert it to a HashSet<string>()
?
var hs = new HashSet<string>(Model);
given, Model
is IEnumerable<string>
?
Or, do that in the controller, by converting the List<T>
to HashSet<T>
and then pass it as an IEnumerable<T>
to the model.
or this one:
from y in Model.Distinct() select y
Upvotes: 0