2016-04-14 23 views
0

嘗試使用MVC 6和EF代碼優先設計顯示嵌套列表。我使用這個Tutorial讓我開始使用MVC,並試圖把它帶到另一個層面。如何顯示嵌套列表並維護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

enter image description here


現在我想顯示像下面的圖像的每個位置在分位置。用戶可以添加綁定到某個位置的新位置或子位置。

enter image description here


顯示的位置列表很簡單: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並顯示我的主類的子類中的嵌套列表?

回答

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); 
+1

這很好,我喜歡它是多麼乾淨。我一直試圖通過一種單獨的方法來獲取數據,但沒有意識到我只是將它傳遞給主視圖。燈泡的時刻。謝謝! –