Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. DC
    • -Batman
    • -Superman
    • -Aquaman
  2. Marvel
    • -Spiderman
    • -Ironman
    • -Thor

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
199 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...