【问题标题】:How to display nested list and maintain MVC pattern?如何显示嵌套列表并维护 MVC 模式?
【发布时间】:2016-04-15 04:20:17
【问题描述】:

尝试使用 MVC 6 和 EF 代码优先设计显示嵌套列表。我正在使用这个Tutorial 让我开始使用 MVC,并试图将它提升到另一个层次。

类:

public class Location
{
    [Key]
    public int ID { get; set; }
    public string LocationName { get; set; }
    public ICollection<SubLocation> Sublocations { get; set; }
    }
}

public class SubLocation
{
    public int ID { get; set; }
    public string SubLocationName { get; set; }
}

运行dnx ef database update 正确设置了我的EF 数据库,并在SubLocation 下为LocationID 分配了一个外键。


现在我想在每个位置下显示子位置,如下图所示。用户可以添加与位置相关的新位置或子位置。


显示位置列表很简单:return View(_context.Location.ToList());

要显示子位置的嵌套列表,我应该在控制器还是视图中完成这项工作?

我希望我可以使用如下视图,但 item.Sublocationsnull,原因我不确定,因为数据库中有数据。:

@foreach (var item in Model) {
  <tr>
    <td>@Html.DisplayFor(modelItem => item.LocationName)</td>
  </tr>

  @foreach (SubLocation itm in item.Sublocations)
  {
    <tr>
        <td>@itm.SubLocationName</td>
    </tr>
  }
}

我尝试在控制器中创建查询,但外键无法用于比较。

var test = (from m in _context.SubLocation
            where m.LocationID == curLocID   <-- m.LocationID isn't available
            select m.SubLocationName
            ).ToList();  

即使我可以使用 LocationID,我也不确定如何将当前位置 (curLocID) 从视图发送回控制器。我想我需要一个辅助方法,但我开始绕圈子了。

如何维护正确的 MVC 并从我的主类的子类显示嵌套列表?

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    您应该考虑将LocationID 属性添加到您的SubLocation 类,这将是Location 表的外键。

    public class SubLocation
    {
        public int ID { get; set; }
        public string SubLocationName { get; set; }
        public int LocationID { set;get;}
    }
    

    现在,查询位置。位置具有SubLocations 属性,因此您的视图应该可以正常工作。

    var locations = _context.Locations.Include(s=>s.SubLocations).ToList();
    return View(locations);
    

    【讨论】:

    • 效果很好,我喜欢它的干净程度。我一直试图通过单独的方法获取数据,但没有意识到我可以将它与主视图一起传递。灯泡时刻。谢谢!
    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2014-10-10
    • 2017-12-28
    相关资源
    最近更新 更多