ASP.NET MVC 3 Razor递归功能 [英] ASP.NET MVC 3 Razor recursive function
问题描述
好的,我想显示一个包含列表列表的列表...
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< MyObject>.我想显示此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屋!