Ste*_*nyi 3 asp.net-mvc recursion razor asp.net-mvc-4
我的视图模型包含一个对象,我需要迭代该对象并为其每个属性显示一些 HTML(我正在为用户提供一种使用 @Model 语法编译 razor 消息的方法)。仅当属性具有必要的属性时才会显示(这部分有效)。然而,递归似乎没有按预期发生。
当调试并单步执行递归调用时,我看到应该递归到的字段是,但调用函数被跳过。也就是说,跟随指针显示当前正在执行的代码行,如果指针直接从开括号跳到闭括号(请注意,使用递归调用的正确参数),而无需在其间执行任何操作。
@helper OutputProperties(Type type, string path)
{
<ul>
@foreach (var info in type.GetProperties())
{
var attrib = info.IsDefined(typeof(RazorAccessibleAttribute), false);
if (attrib)
{
<li>
@if (@IsTypePrimitive(info.PropertyType))
{
<a data-value="@(path + "." + info.Name)">@info.Name</a>
}
else
{
<a data-value="@(path + "." + info.Name)" href="#">@info.Name</a>
}
</li>
if (!@IsTypePrimitive(info.PropertyType))
{
OutputProperties(info.PropertyType, path + "." + info.Name);
}
}
}
</ul>
}
Run Code Online (Sandbox Code Playgroud)
我测试了一个简单的递归函数,这也毫无价值,而且也失败了。
@helper recurseTest()
{
recurseTest();
}
Run Code Online (Sandbox Code Playgroud)
同样,没有堆栈溢出(heh)错误,因为递归实际上从未发生过。我在调用前使用 @ 和不使用 @ 测试了我的函数(不确定有什么区别)。
在内部方法前面添加“@”应该可以解决它......
@OutputProperties(info.PropertyType, path + "." + info.Name);
Run Code Online (Sandbox Code Playgroud)
更新:完整的测试代码,对原始代码进行了微小的更改
@helper OutputProperties(Type type, string path)
{
<ul>
@foreach (var info in type.GetProperties())
{
var attrib = true;//info.IsDefined(typeof(RazorAccessibleAttribute), false);
if (attrib)
{
<li>
@if (info.PropertyType.IsPrimitive)
{
<a data-value="@(path + "." + info.Name)">@info.Name</a>
}
else
{
<a data-value="@(path + "." + info.Name)" href="#">@info.Name</a>
}
</li>
if (!@info.PropertyType.IsPrimitive)
{
@OutputProperties(info.PropertyType, path + "." + info.Name);
}
}
}
</ul>
}
<p>
@OutputProperties(typeof(MvcTestBench.Models.ManagerUser), "Model")
</p>
Run Code Online (Sandbox Code Playgroud)