【问题标题】:Building Table of Contents MVC nested models构建目录 MVC 嵌套模型
【发布时间】:2017-05-31 15:27:54
【问题描述】:

给定一个包含以下内容的目录:

类别, 部分, 主题,

我创建了以下 3 个模型:

public class Category
{
    public int id { get; set; }
    public string name { get; set; }
    public ICollection<Section> Sections { get; set; }
}
public class Section
{
    public int id { get; set; }
    public string name { get; set; }
    public int CategoryId { get; set; }
    public ICollection<Topic> Topics { get; set; }
}
public class Topic
{
    public int id { get; set; }
    public string name { get; set; }
    public int SectionId { get; set; }
}

在 SQL Mgmt Studio 中,我创建了 3 个表之间的一对多关系。我的控制器 ActionResult 如下所示:

public ActionResult Index()
{
    return View(_db.Categories.ToList());
}

然后是我的观点:

@model IEnumerable<Models.Category>

<h2>Table of Contents</h2>

<ul>
@foreach (var item in Model)
{
    <li>@Html.DisplayFor(model => item.name)
        @if (item.Sections != null)
        {
            <ul>
            @foreach (var sec in item.Sections)
            {
                <li>@Html.DisplayFor(model => sec.name)
                    @if (sec.Topics != null)
                    {
                        <ul>
                        @foreach (var topic in sec.Topics)
                        {
                            <li>@Html.DisplayFor(model => topic.name)</li>
                        }
                        </ul>
                    }
                </li>
            }
            </ul>   
        }
    </li>
}
</ul>

我只从 Category 表中获取数据。因此它正确地抓取了类别数据并构建了外部列表,但它没有填充模型中的相关部分和主题。我做错了什么?

尝试在下面的 cmets 中根据 David Clough 的建议实施答案。在我的 Controller 中引用 System.Data.Entity 后,lambda 表达式版本能够编译和运行,但它在尝试访问模型的 foreach 循环中产生错误。 InnerException 中的错误是:“列名'Section_id'无效。\r\n列名'Category_id'无效。\r\n列名'Section_id'无效。”

这是我对控制器所做的更改:

public ActionResult Index()
{
    var TOC = _db.Categories.Include(c => c.Sections.Select(s => s.Topics));
    return View(TOC);
}

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

我没有弄清楚如何使用嵌套模型。相反,我使用的是局部视图,这似乎工作正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2012-08-28
    • 2017-01-29
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多