RenderSection()内部部分与母版页

我在主页面(布局)中添加了部分“侧边栏”,在我正在使用的部分内部:

@RenderSection("SearchList", required: false) 

在其中一个使用我正在做的母版页的视图中:

 @section SearchList { // bunch of html } 

但它给了我错误:

无法直接请求文件“〜/ Views / Shared / _SideBar.cshtml”,因为它调用“IsSectionDefined”方法。

这有什么不对?

Razor目前不支持您尝试做的事情。 节仅在视图页面及其直接布局页面之间起作用。

在创建布局视图时,您可能希望将某些部分分别放入部分视图中。

您可能还需要渲染需要放入其中一个局部视图的标记中的节。 但是,由于部分视图不支持RenderSection逻辑,因此您必须解决此问题。

通过将“布局”页面中的RenderSection结果作为局部视图的模型传递,可以在局部视图中渲染节。 您可以通过在_Layout.cshtml中放置这行代码来完成此操作。

_Layout.cshtml

 @{ Html.RenderPartial("_YourPartial", RenderSection("ContextMenu", false));} 

然后在_YourPartial.cshtml中,您可以在_Layout视图的Html.RenderPartial调用中呈现作为模型传递的部分。 您检查模型是否为空,以防您的部分不需要。

_YourPartial.cshtml

 @model HelperResult @if (Model != null) { @Model } 

用剃刀助手可以解决这个问题。 它有点优雅 – hacky™,但它为我做了工作。

因此在父视图中定义一个帮助器:

 @helper HtmlYouWantRenderedInAPartialView() { Attention! } 

然后,当您渲染部分时,将此助手传递给它

 @Html.Partial("somePartial", new ViewDataDictionary { { "OptionalSection1", (Func)(HtmlYouWantRenderedInAPartialView) } }) 

然后在局部视图中,你可以像这样调用这个帮助器

 
@ViewData.RenderHelper("OptionalSection1")

最后,您需要使用此扩展方法来简化“调用”部分

 public static HelperResult RenderHelper(this ViewDataDictionary viewDataDictionary, string helperName) { Func helper = viewDataDictionary[helperName] as Func; if (helper != null) { return helper(); } return null; } 

所以重点是传递这个帮助器的委托,然后当子视图调用它时,内容会在你想要的地方呈现。

子视图的最终结果如下所示

 
Attention!