views:

543

answers:

3

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.

Thanks,

Mike

A: 

What you should probably do is have a Custom Type with your list of Categories, and each item has a property where the sub-items are contained.

This can be easily achieved in Entity Framework, using Navigation Properites.

Tomas Lycken
A: 

I would set up the Category Model class with an items property of type IEnumerable<item>.

Then include an IEnumerable<subItem> subItems property on the item class.

The view would iterate through these items and sub items very easily.

Edit: actually if sub items are exactly the same as items, then there could just be a single item class with an IEnumerable<item> subItems property. This would also allow for unlimited levels of sub items.

Dennis Palmer
+3  A: 

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.

Matt Hinze
This seems to be what Dennis was suggesting. Thanks for the advice.
mikerennick