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

时间:2011-10-03 12:49:51

标签: asp.net-mvc hierarchy

我在数据库中有一个表,它有一个自己的外键。在添加产品时,我希望用户能够从DropDownList中选择一个类别。现在,我能够显示如下结果::


  • 电子
  • MP3播放器

但是,如果像这样显示它们将是理想的,因为MP3播放器是电子产品的孩子: -

  • 电子
    • MP3播放器

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

    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 个答案:

答案 0 :(得分:1)

看起来你需要optgroups。不幸的是,MVC没有本机支持。所以如下文所述,你可以自己写一个:

ASP.Net MVC 3: optgroup support in Html.DropDownListFor

相关问题