0

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.

enter image description here


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.

enter image description here


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 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That worked great and I like how clean it is. I kept trying to get the data through a separate method not realizing I could just pass it with the main view. Light bulb moment. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.