问题
Attempting to display nested list using MVC 6 and EF code first design. I'm using this Tutorial to get me started with MVC and am trying to take it to another level.
Classes:
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; }
}
Running dnx ef database update sets up my EF database correctly and assigns a foreign key to LocationID under SubLocation.
Now I want to display Sub Locations under each Location like the following image. The user can add new locations or sub locations tied to a location.
Displaying the list of locations is simple: return View(_context.Location.ToList());
To display the nested list of sub-locations, should I do the work in the controller or view?
I was hoping I could just use the view like the following but item.Sublocations is null for a reason that I'm not sure of since there is data in the database.:
@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>
}
}
I've tried creating a query in the controller but the foreign key isn't available to compare against.
var test = (from m in _context.SubLocation
where m.LocationID == curLocID <-- m.LocationID isn't available
select m.SubLocationName
).ToList();
Even if I could use the LocationID I'm not sure how to send the current Location (curLocID) from the View back to the controller. I think I need a helper method but I'm starting to go in circles.
How can I maintain proper MVC and display nested list from a subclass of my main class?
回答1:
You should consider adding a LocationID property to your SubLocation class which will be the foreign key to the Location table.
public class SubLocation
{
public int ID { get; set; }
public string SubLocationName { get; set; }
public int LocationID { set;get;}
}
Now, query the locations. Location has a SubLocations property,so your view should work fine.
var locations = _context.Locations.Include(s=>s.SubLocations).ToList();
return View(locations);
来源:https://stackoverflow.com/questions/36633116/how-to-display-nested-list-and-maintain-mvc-pattern