Search code examples
asp.net-mvcnestedhierarchical

.Net MVC Passing Nested Data from Controller to View


I am creating a .NET MVC application and I have a view in which I want to display the following:

Category

followed by a list of items for the current Category

[possibly] followed by a list of sub items for the current item

I could create a custom ViewModel class that sends 3 separate IEnumerable lists (categories, items, and sub items). The problem with this approach is there is no easy way to render the data in the proper order (hierarchy) in the view. With this approach I would have three lists, and then need to add conditional logic during rendering. This would mean that each item list would be iterated multiple times as I try to slot the items into the proper positions on the page.

I would rather pass back the data in the proper order, perhaps as an XML file. What is the proper approach here?

I have also contemplated concatenating the data in the controller and passing the formatted text to the view, but this seems to violate the notion of having the view handle rendering.


Solution

  • I would stay away from XML here. Pass the proper hierarchy; that seems reasonable:

    public class ViewModel
    {
        Category[] Categories { get; set; }
    }
    
    public class Category
    {
        Item[] Items { get; set; }
    }
    
    public class Item
    {
        Item[] SubItems { get; set; }
    }
    

    then you can have nested foreach loops inside your view.