Performance considerations with nested declarative @helpers in Razor

余生长醉 提交于 2020-01-24 10:06:29

问题


@helpers, along with partial views allow for great composability, however I would like to know if there is a significant performance cost to be aware. For example:

App_Code\Wrappers.cshtml:

@helper HeaderWrapper(WebViewPage view, Func<object, HelperResult> content,Func<object, HelperResult> navbar = null) {
  <div class="container-fluid">
   @content(null)
  </div>

if (navbar != null) {
    <div class="container-fluid">
      <nav id="navbar-page" class="navbar-default navbar-collapse collapse" role="navigation">
        <ul class="nav navbar-nav nav-pills">
          @navbar(null)
        </ul>
      </nav>
    </div>
}
}

App_Code\Helpers.cshtml:

@* Logo based on Font Awesome icon *@
@helper PageHeaderLogo(FA icon) { 
  @PageHeaderLogo2(@<text>
        <i class="fa fa-@icon"></i>
    </text>)
}

@helper PageHeaderLogo2(Func<object, HelperResult> content) { 
    <div class="bm-logo">
      @content(null)
    </div>
}

Views\Home\index.cshtml:

@section SECTION_HEADER{
  @Wrappers.HeaderWrapper(this,
  @<text>
    <div>static html</div>
    @Helpers.PageHeaderLogo(FA.star) 
  </text>,
  @<text>
    <div>my navbar</div>
  </text>)
}

In this example, if you look at the actual view, the composition goes like so: 1. @Helpers.PageHeaderLogo is called 2. @Helpers.PageHeaderLogo calls @Helpers.PageHeaderLogo2 3. When @Helpers.PageHeaderLogo returns, @Wrappers.HeaderWrapper is called. 4. When @Wrappers.HeaderWrapper returns, the whole section SECTION_HEADER is then rendered into layout.

And that's just a relatively simple example with no partial views.

So my questions are:

  1. Is this a good approach for composing "functions" (helpers) and staying DRY?
  2. Won't it negatively impact performance (I am coming from webforms, and you could not do those things there, but I wonder if it will slow down html generation by several times compared with web forms (I never used viewstate btw on webforms))?
  3. Helpers that can take in html / razor html apparently must have parameter of type Func<object, HelperResult> content, which then they can render with @content(null) when called as shown above. Is this the proper approach, or am I doing something wrong? I mean the null passed as argument into the "content" which itself was only an argument to the @helper - this looks kind of weird. You would expect it to be something akin to just regular string.

Thanks.

来源:https://stackoverflow.com/questions/41986198/performance-considerations-with-nested-declarative-helpers-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!