asp.net-mvc - MVC Razor @helper 函数无法正确递归?

标签 asp.net-mvc asp.net-mvc-4 razor recursion

我的 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/

相关文章:

c# - 在我看来,什么时候应该从数据库中查询,ASP.NET MVC

c# - 如何在 MVC 4 中创建图像按钮

javascript - cshtml 页面 MVC 中的简单 javascript

c# - ASP.NET MVC。 Ajax.BeginForm OnSuccsess 找不到 javascript 函数

.net - 如何将分层数据从 DataTable 转换为 JSON

c# - 如何防止编辑器弹出窗口关闭?

c# - 通过复选框以编程方式为 MVC 4 中的用户分配角色

asp.net-mvc - MVC HandleError 过滤器未捕获异常

c# - 解析来自 API 的动态 jsonResult 响应给出 "object does not contain definition for X"

asp.net-mvc - global.asax Application_AcquireRequestState 与 Application_BeginRequest