C# 单下拉列表中的类别和子类别for-MVC Razor
我有一个带有类别Id和父类别Id的表C# 单下拉列表中的类别和子类别for-MVC Razor,c#,asp.net-mvc-4,razor,dropdownlistfor,C#,Asp.net Mvc 4,Razor,Dropdownlistfor,我有一个带有类别Id和父类别Id的表 Category Id Category Name Parent Category Id 1 Desktop 0 2 PC 1 3 Mac 1 如何以以下格式在dropdownlist中返回它: 我能想到的最好的办法是创建一个类来保存下拉列表的名称和值,并使用它在
Category Id Category Name Parent Category Id
1 Desktop 0
2 PC 1
3 Mac 1
如何以以下格式在dropdownlist中返回它:
我能想到的最好的办法是创建一个类来保存下拉列表的名称和值,并使用它在操作中创建一个SelectList
public class SelectListValue{
public string Text {get;set;}
public string Value {get;set;}
}
public ActionResult SomeActionMethod()
{
var categories = GetCategories() //Get your list of categories
var selectListItems = new List<SelectListValue>();
foreach(var item in categories)
{
var text = GetCategoryDisplay() //You will need to figure out how to generate the text, like Components > Web Cameras. This doesn't need to be a method. It could be a property on the Category object.
selectListItems.Add(new SelectListValue {Text = text, Value = item.CategoryId.ToString()});
}
ViewData["CategoryList"] = new SelectList(selectListItems, "Value", "Text");
}
这应该行得通,或者至少是类似的东西。嗨,伙计,我找了这么多,但没找到,但最后我自己编码了 我会告诉你我是如何解决这个问题的,就像你的截图一样。这是我的 这是我的分类模型,它与你的模型几乎相同
公共类类别
{
公共int ID{get;set;}
公共字符串CategoryName{get;set;}
public int?ParentID{get;set;}
[ForeignKey(“ParentID”)]
公共虚拟ICollection子类别{get;set;}
}
您希望每个项目的价值是多少?@b是的,我不明白您所说的“您希望每个项目的价值是多少”是什么意思。我想返回一个查询,以该格式填充dropdownlist,例如类别Id-->父类别Id。
@Html.DropDownListFor(x => x.CategoryId, ViewData["CategoryList"] as SelectList)