使用Func<>创建递归方法助手

时间:2018-01-11 15:53:14

标签: razor asp.net-core html-helper asp.net-core-2.0

我有两个带有签名的方法助手:

  

@helper CreateNavigation(int parentId,int depthNavigation)

     

@helper Navigation(int parentId,int depthNavigation)

我尝试将其转换为在ASP.NET Core 2中使用的正确方法。

但我在VS2017 IDE中收到的错误是:

  

1-使用未分配的局部变量'导航'
  2-局部变量   在访问

之前,可能无法初始化“导航”

我该如何解决?

@using Microsoft.AspNetCore.Html
@using Microsoft.AspNetCore.Mvc.Razor
@model List<Jahan.Beta.Web.App.Models.Comment>

@{
    Func<int, int, int, HelperResult> CreateNavigation
        = (parentId, depthNavigation) => new Func<object, HelperResult>(
    @<text>@{
                Comment parent = Model.SingleOrDefault(r => r.Id == parentId);
                depthNavigation = 6;
        @Navigation(parentId, depthNavigation)
    }</text>)(null);
}
@{

    Func<int, int, HelperResult> Navigation
        = (parentId, depthNavigation) => new Func<object, HelperResult>(
    @<text>@{
                var parent = Model.Children(parentId);
                if (//condition)
                {
                    if (//condition)
                    {
                        foreach (var comment in Model)
                        {
                            if (//condition)
                            {
                                <li><p>@comment.Description</p></li>
                                @Navigation(comment.Id, depthNavigation)
                            }
                        }
                    }
                }
    }</text>)(null);
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我能够通过首先声明委托并将其设置为null,然后添加如下实现来解决此问题:

@{Func<IEnumerable<Foo>, IHtmlContent> DisplayTree = null;}
@{DisplayTree = @<text>@{
  var foos = item;
  <ul>
  @foreach (var foo in foos)
  {
  <li>
    @foo.Title
    @if (foo.Children.Any())
    {
      @DisplayTree(foo.Children)
    }
  </li>
  }
  </ul>
}</text>;}


@DisplayTree(new List<Foo>{...})