在.net MVC中呈现列表的子列表 [英] Rendering a sublist of a list in .net MVC

查看:39
本文介绍了在.net MVC中呈现列表的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习.net MVC,也许没有正确搜索我需要找到解决方案的东西.

I'm still learning .net MVC, and perhaps am not searching correctly for what I need to find a solution to.

简而言之,我在数据库中有一个表,其结构为:

In short, I have a table in the database that is structured as:

ID    Category    Subcategory    FK

因此,每个类别以及每个子类别都可能出现多次,这对于该类别来说是唯一的.

So each category may appear multiple times, as well as each subcategory, which is unique to the category.

我想在如下视图中呈现菜单:

I want to render a menu in the view that looks like:

Category 1
    Subcategory 1a
    Subcategory 1b
    Subcategory 1c
Category 2
    Subcategory 2a
    Subcategory 2b

以此类推.现在在控制器中,我有:

And so on. Right now in the controller I have:

var categories = db.Category
                     .Where(oa => oa.Category != "")
                     .GroupBy(oa => new { oa.Category, oa.Subcategory })
                     .Select(oa => oa.FirstOrDefault());

但是,我不确定如何执行视图中想要实现的目标.我知道我必须以某种方式遍历列表,但不确定如何.我知道它涉及以下方面:

However, I'm not sure how to do what I want to achieve in the view. I know I have to loop through the list somehow, but I'm not sure how. I know it involved something along the lines of:

@foreach (var item in Model)
{
    <li>
        <a id="@item.ID" href="#">@item.Category</a>
    </li>
}

但是我只希望每个类别都出现一次,然后让所有子类别都出现在父类别下.还是我需要更改控制器及其发送数据的方式?

But I only want each category to appear once, and then need all subcategories to appear under the parent category. Or maybe I need to change the controller and how it sends the data?

推荐答案

首先创建一个简单的视图模型来表示您要在视图中显示的内容

Start by creating a simple view model to represent what you want to display in the view

public class CategoryVM
{
    public string Name { get; set; }
    public IEnumerable<string> SubCategories { get; set; }
}

然后将查询投影到该视图模型的集合中,然后将其返回到视图

Then project your query to a collection of that view model and return it to the view

var model = db.Category.Where(x => x.Category != "")
    .GroupBy(x => x.Category).Select(x => new CategoryVM
    {
        Name = x.Key,
        SubCategories = x.Select(y => y.Subcategory)
    });
return View(model);

并在视图中

@model IEnumerable<CategoryVM>
....
@foreach(var category in Model)
{
    <h2>@category.Name</h2>
    <ul>
        @foreach(var subCategory in category.SubCategories)
        {
            <li>@subCategory</li>
        }
    </ul>
}

这篇关于在.net MVC中呈现列表的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆