ASP.NET MVC 3 Razor 递归函数 [英] ASP.NET MVC 3 Razor recursive function

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

问题描述

好的,所以我想显示一个包含列表列表的列表...

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

现在这些对象中的每一个都有一个 List.我想显示此 div 下方的每个级别,例如每个级别都有一个制表符缩进.

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.

我想这里可以使用 Razor 函数,但我需要一些帮助来形成它.这是我的想法:

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

推荐答案

Razor 视图引擎允许使用 @helper 关键字编写内联递归助手.

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

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

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