在 ASP.NET MVC 中的 HTML.DropDownList Helper 方法中显示分层数据
我在数据库中有一个表,它本身有一个外键。在添加产品时,我希望用户能够从 DropDownList 中选择一个类别。现在,我可以显示如下结果 ::
- Electronics
- MP3 Players
但是,如果像这样显示那就更理想了,因为 MP3 Player 是一个孩子电子学:-
- 电子
- 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您需要 optgroups。不幸的是,MVC 对此没有本机支持。因此,正如下面的文章中提到的,您可以自己编写一个:
ASP .Net MVC 3:Html.DropDownListFor 中的 optgroup 支持
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