Mvc从类别ID获取子类别

时间:2015-07-14 09:25:51

标签: c# sql model-view-controller

我有2个sql表类别和子类别。在Subcategories表中有CategoryID行。我怎样才能获得categoryid的子类别?

public ActionResult Index()
{
  var model = new BlogDB();
  model.Categories = db.Categories.ToList();
  model.Subcategories = db.Subcategories.ToList();
  return View(model);
}

我想这样:

select c.Name, s.Name from Categories c left join Subcategories s on c.ID=s.CategoryID

索引视图是:

<ul>
    @foreach (var item in Model.Categories)
    {
        <li>
            @item.Name
            <ul>
                @foreach (var sub in Model.Subcategories)
                {
                    <li>@sub.Name</li>
                }
            </ul>
        </li>
    }
</ul>

1 个答案:

答案 0 :(得分:2)

如果您的数据模型设置正确,并假设您的类别类具有子类别的ICollection

public call Category
{
   //.
   //.
   //.
   public virtual List<Subcategory> Subcategories{get;set;}    
}

<ul>
    @foreach (var item in Model.Categories)
    {
        <li>
            @item.Name
            <ul>
                @foreach (var sub in item.Subcategories)
                {
                    <li>@sub.Name</li>
                }
            </ul>
        </li>
    }
</ul>