我的 View 模型包含一个对象,我需要遍历该对象并为其每个属性显示一些 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>
}
同样毫无值(value)的是我测试了一个简单的递归函数,但它也没有工作。
@helper recurseTest()
{
recurseTest();
}
同样,没有计算器溢出(嘿)错误,因为递归实际上从未发生过。我在调用前使用 @ 和不使用 @ 测试了我的函数(不确定有什么区别)。
最佳答案
在内部的方法前添加“@”应该会处理它......
@OutputProperties(info.PropertyType, path + "." + info.Name);
更新: 对原始代码稍作改动,完成测试代码
@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>
关于asp.net-mvc - MVC Razor @helper 函数无法正确递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068285/