嵌套模型在View中返回null

时间:2015-07-23 13:32:04

标签: c# asp.net-mvc model null

我知道之前已经问过这个问题,但我正在努力寻找合适的解决方案。我有一个foreach loop来比较2个模型的值,并决定每个属于哪个父元素,就像你在我的视图中看到的那样(表具有扩展/关闭功能)所以我希望每个组都显示在它们已经存在的部分下面分配给,但是当我调用item.Group.GroupSectionID时,它每次都返回null,但是在调试时,控制器正在填充GroupDetail模型并且正在填充SectionDetail模型,但是public GroupDetail Group { get; set; }返回null:

查看(SectionTable)

<table class="table table-striped">
    <tbody>
    <!-- Render the details of each employee. -->
    @foreach (var item in Model)
    {
    <tr>
        <td>-</td>
        <td>@Html.DisplayFor(model => item.Name)</td>
    </tr>

    if (item.Group.GroupSectionID != 0 && item.SectionID == item.Group.GroupSectionID)
    {
    <tr>
        <td colspan="3"><p>@Html.DisplayFor(model => item.Group.GroupName)</p></td>
    </tr>
    }
    }

    </tbody>
</table>

控制器

public ActionResult GroupTable()
{
    Manager manager = new Manager();
    var data1 = manager.GetAllGroups();
    var groupDetails = from u in data1
    select new GroupDetail
    {
        GroupID = u.Id,
                GroupDescription = u.Description,
                GroupName = u.Name,
                GroupSectionID = u.SectionId,
                SectionName = u.SectionName
    };
    return View(groupDetails.ToList());
}

public ActionResult SectionTable()
{
    Manager manager = new Manager();
    var data3 = manager.GetAllSections();
    var sectionDetails = from u in data3
    select new SectionDetail
    {
        SectionID = u.Id,
                Name = u.Name,
                Description = u.Description
    };
    return View(sectionDetails.ToList());
}

模型

public class SectionDetail
{
    public int SectionID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public GroupDetail Group { get; set; }

}

public class GroupDetail
{
    public int GroupID { get; set; }
    public string GroupDescription { get; set; }
    public string GroupName { get; set; }
    public int GroupSectionID { get; set; }
    public string SectionName { get; set; }
}

提前致谢,如果您想了解更多信息,请询问。

1 个答案:

答案 0 :(得分:2)

您不在此处指定Group属性:

var sectionDetails = from u in data3
                     select new SectionDetail
                               {
                                   SectionID = u.Id,
                                   Name = u.Name,
                                   Description = u.Description,
                                   Group = u.Group
                               };