在ASP.NET MVC中的HTML.DropDownList Helper方法中显示分层数据

问题描述:

我在数据库中有一个表,该表本身具有外键.在添加产品产品时,我希望用户能够从DropDownList中选择一个类别.现在,我可以显示如下结果::

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 ::

  • 电子
  • MP3播放器
  • Electronics
  • MP3 Players

但是,如果这样显示它们,将是理想的,因为MP3 Player是Electronics的子代:-

But, it would be ideal if they are shown like this, since MP3 Player is a child of Electronics :-

  • 电子
    • MP3播放器
    • Electronics
      • MP3 Players

      如何在DropDownList中实现此目标?我当前用于检索和显示的代码分别如下:-

      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>
      

您似乎需要optgroup.不幸的是,MVC对此没有原生支持.因此,如以下博文所述,您可以自己写一个:

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:HTML中的optgroup支持. DropDownListFor