Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Okay, so I want to display a list containing lists of lists of lists...

I have no way of knowing how many levels there are to display, so I figured this is where I break out the old recursive routine.

I'm having trouble with exactly how to go about this though.

This is what I have so far (in view - simplified):

@foreach(MyObject item in @Model.ListOfObjects){ 
    <div> @item.Title </div>
    //Call recursive function?
}

Now each of these objects also have a List<MyObject>. I want to display each level below this div, with a tab indent per level for instance.

I was thinking a Razor function would be the thing to do here, but I need some help in forming it. Here's my thinking:

@functions{
    public static void ShowSubItems(MyObject _object){
         if(_object.ListOfObjects.Count>0){
             foreach(MyObject subItem in _object.listOfObjects){

                 // Show subItem in HTML
                 ShowSubItems(subItem);
             }
         }
     }
 }

But as you can see, I plainly need some help :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

The Razor view engine allows to write inline recursive helpers with the @helper keyword.

@helper ShowTree(IEnumerable<Foo> foos)
{
    <ul>
        @foreach (var foo in foos)
        {
            <li>
                @foo.Title
                @if (foo.Children.Any())
                {
                    @ShowTree(foo.Children)
                }
            </li>
        }
    </ul>
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...