Displaying hierarchical data in HTML.DropDownList Helper method in ASP.NET MVC

强颜欢笑 提交于 2019-12-11 18:17:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!