.Net MVC Transfer of embedded data from the controller to view mode

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

Category

and then a list of items for the current category

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

I could create my own ViewModel class that will send 3 separate IEnumerable lists (categories, items and sub-items). The problem with this approach is that there is no easy way to display data in the correct order (hierarchy) in the view. With this approach, I would have three lists, and then I would need to add conditional logic during rendering. This would mean that each list of elements would be repeated several times when I try to stack the elements in the corresponding positions on the page.

I would rather pass the data in the correct order, perhaps as an XML file. What is the right approach?

I also considered the possibility of concatenating the data in the controller and passing the formatted text to the view, but this seems to violate the idea of ​​rendering the view descriptor.

+3
source share
3 answers

I would stay away from XML here. Pass the correct hierarchy; which 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 loops foreachinside your view.

+3
source

What you probably should do is have a Custom type with your list of categories, and each element has a property that contains sub-items.

This can be easily achieved in the Entity Framework using the Navigation functions .

0
source

Model Model items IEnumerable<item>.

IEnumerable<subItem> subItems item.

.

Edit: in fact, if the subtable exactly matches the elements, then there can only be one class itemwith a property IEnumerable<item> subItems. It will also allow an unlimited number of additional items.

0
source

Source: https://habr.com/ru/post/1708835/


All Articles