问题
I have a table in database that has a foreign key to itself. While adding product products I want the users to be able to select a category from DropDownList. Right now, I am able to show the result like following ::
- Electronics
- MP3 Players
But, it would be ideal if they are shown like this, since MP3 Player is a child of Electronics :-
- Electronics
- MP3 Players
How can I achieve this in a DropDownList ? My current code for retrieving and displaying is following respectively :-
public ActionResult Create()
{
ViewBag.ParentCategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
return View();
}
CSHTML
<div class="editor-field">
@Html.DropDownList("ParentCategoryID", String.Empty)
@Html.ValidationMessageFor(model => model.ParentCategoryID)
</div>
回答1:
It looks like you need optgroups. Unfortunately MVC has no native support for this. So as mentioned in the following post you can write one yourself:
ASP.Net MVC 3: optgroup support in Html.DropDownListFor
来源:https://stackoverflow.com/questions/7635191/displaying-hierarchical-data-in-html-dropdownlist-helper-method-in-asp-net-mvc