Tutorial :.Net MVC Passing Nested Data from Controller to View



Question:

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

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.


Solution:2

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.


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »