Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c# - Create DropDownList using Iteration Loop

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...