Using @section inside Razor Helper

∥☆過路亽.° 提交于 2019-12-10 14:49:51

问题


We are trying to setup Sections of our layout to be Required but configurable based on the individual page. At the moment we do this with a Section.

@section FloatingNav {
    <h1>@Model.Name <span class="release-year">@Model.AverageRating</span></h1>
    <ul class="sub-nav">
        <li class="active"><a href="#episodes">Episodes</a></li>
        <li><a href="#episodes">Cast</a></li>
        <li>Reviews</li>
        <li>Related</li>
    </ul>
}

This requires you to setup this block in every new page but i wanted to make this process easier with some defaults and options to configure using a partial view. I was hoping to setup a Razor helper such as this.

@using System.Web.Mvc.Html
@helper FloatingNav(string name, int rating) {
    @section FloatingNav {
        <h1>
            name <span class="release-year">rating</span></h1>
        <ul class="sub-nav">
            <li class="active"><a href="#episodes">Episodes</a></li>
            <li><a href="#episodes">Cast</a></li>
            <li>Reviews</li>
            <li>Related</li>
        </ul>
    }
}
@helper FloatingNav(System.Web.Mvc.HtmlHelper html, string viewName) {
    @section FloatingNav {
        @html.Partial(viewName)
    }
}
@helper FloatingNav(System.Web.Mvc.HtmlHelper html, string viewName, object model) {
    @section FloatingNav {
        @html.Partial(viewName, model)
    }
}

So the syntax to implement would be something like

@Layout.FloatingNav(@Model.Name, @Model.AverageRating)

or

@Layout.FloatingNav("_SimpleNav", @Model)

The issue though is that it seems the Razor Helpers do not understand the section syntax. Is there a way to include sections in Razor Helpers?


回答1:


I don't think this is possible.

The @helper and @section syntax are special directives for compiling pages.

A HelperResult (a helper) doesn't know how to define a section.

The DefineSection method belongs to a WebPageBase.

You might have to come at this from a different direction. Using partial views instead of helpers would probably fix this problem.



来源:https://stackoverflow.com/questions/22977339/using-section-inside-razor-helper

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