0

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>
Pankaj Upadhyay
  • 12,966
  • 24
  • 73
  • 104

1 Answers1

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

Community
  • 1
  • 1
Atacan
  • 948
  • 9
  • 10