ASP MVC在一个视图中检索数据

时间:2015-02-14 12:05:07

标签: asp.net-mvc

我是ASP.NET MVC的新手,我对如何在View中显示我需要的数据感到困惑。在第一页,我想显示新添加的产品和类别。到目前为止,我设法获得主要类别并将它们发送到视图。以下是我到目前为止所做的事情。

HomeController.cs

public ActionResult Index()
{
List<CategoriesViewModel> mainCategories = (from cat in db.Categories
                                  where cat.ParentID == null
                                  orderby cat.Name
                                  select new CategoriesViewModel { Name = cat.Name}).ToList();

return View(mainCategories);
}

Categories.cs

public class CategoriesViewModel
{
  public string Name { get; set; }
}

public class ItemsDBContext : DbContext
{
  public DbSet<CategoriesViewModel> Items { get; set; }
}

Index.cshtml

@model List<Website.Models.CategoriesViewModel>
...
<ul>
@foreach(var item in Model) {
<li><a href="#">@item.Name</a></li>
}
</ul>

现在,如果我想展示顶级产品,应该做些什么?任何帮助将是欣赏它。

1 个答案:

答案 0 :(得分:0)

这是如何在不明确创建另一个模型的情况下完成的,因为在您的情况下,您的模型包含的数据是通过父子关系链接的(类别是产品的父级)。

这是一个简短的片段,可以帮助您了解这个想法。

@foreach(var item in Model) {
    // do specific formatting for the way you want to render each category
    foreach(var product in Model.Products){
        // do show product in a way that you prefer
     }
}

仅供将来参考: 如果您没有这种父子关系:您可以通过创建一个包含您希望在模型中使用的两个类的类来解决此问题。虽然,在我看来你应该避免这样做。

相关问题