问题
I will try my best to explain what I am looking for.
Let's say for argument's sake that I have a table in my database that has the properties ID
, Item
, Category
...
the table is populated as so:
================================
|ID| |Item | Category |
================================
| 1 | Batman | DC |
| 2 | Superman | DC |
| 3 | Aquaman | DC |
| 4 | Spiderman| Marvel |
| 5 | Ironman | Marvel |
| 6 | Thor | Marvel |
================================
Now, I want to create a dropdownlist with this information... but seperated by the category..
So it would look like this:
- DC
- -Batman
- -Superman
- -Aquaman
- -Batman
- Marvel
- -Spiderman
- -Ironman
- -Thor
- -Spiderman
Now it doesn't need to be as formatted as shown above but just a simple nested list with the emphasis on the Category
How would I iterate through the table and each time the Category
changes to print that Category text once then print the Item
's that correspond with that Category
underneath it?
回答1:
In MVC-5.2, you can use one of the overloads of SelectList
that accepts string dataGroupField
to group your options. For example, in the controller
model.OptionList = new SelectList(db.MyTable, "ID", "Item", "Category", null);
return View(model);
and in the view
@Html.DropDownListFor(m => m.MyProperty, Model.OptionList)
Alternatively you can build an IEnumerable<SelectListItem>
and set the Group
property, for example
List<SelectListItem> optionList = new List<SelectListItem>
var groups = db.MyTable.GroupBy(x => x.Category);
foreach(var group in groups)
{
var optionGroup = new SelectListGroup() {Name = group.Key};
foreach (var item in group)
{
optionList.Add(new SelectListItem { Value = item.ID.ToString(), Text = item.Item, Group = optionGroup });
}
}
回答2:
If you wanted to output your results as you initially provided, you could accomplish this by using a GroupBy
call and then simply iterating through those groups (and subsequently the items within each group):
@foreach(var group in Model.GroupBy(g => g.Category))
{
<ol>
<li><b>@group.Key</b></li>
<ul>
@foreach(var item in group)
{
<li>- @item</li>
}
</ul>
</ol>
}
This assumes that you already have the objects from your database within your Controller and are simply passing the collection of them into your View. Additionally, this example is performed within the View, which isn't ideal (you preferably want to handle this logic within the actual model itself).
As far as creating a DropDownList goes, you could really do the same if you wanted to preface each entry with its appropriate category :
<select id='Hero' name='Hero'>
@foreach(var hero in Model)
{
<option value='hero.ID'>@hero.Category - @hero.Item</option>
}
</select>
来源:https://stackoverflow.com/questions/36411560/create-dropdownlist-using-iteration-loop