MVC3剃刀递归函数 [英] MVC3 Razor recursive function

查看:164
本文介绍了MVC3剃刀递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我想显示包含列表的列表清单列表...

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. 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 :)

推荐答案

剃刀视图引擎允许写的 @helper inline关键字递归帮手。

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>
}

这篇关于MVC3剃刀递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆