2011-01-30 55 views
27

我有一个部分的“边栏”添加到主网页(布局)和这里面的部分我使用:RenderSection()内的部分与母版页

@RenderSection("SearchList", required: false) 

论的观点一个使用母版页我做:

@section SearchList { 
    // bunch of html 
} 

,但它给我的错误:

The file "~/Views/Shared/_SideBar.cshtml" cannot be requested directly because it calls the "IsSectionDefined" method.

这里有什么错?

回答

21

Razor当前不支持您正在尝试执行的操作。部分仅在查看页面及其即时布局页面之间起作用。

+0

什么解决办法?我有一个布局 - >页面 - >部分。当部分在那里时,我需要引用脚本/布局并将其加载到头部。任何非愚蠢的方式来做到这一点?无论如何,这个限制有什么意义? – Shimmy 2012-11-26 01:33:27

+0

@Shimmy你可以尝试在ViewData中添加某种数据结构,以指定Layout页面应该引用哪些东西。 – marcind 2012-11-26 23:50:47

13

在创建布局视图时,您可能需要将某些部分分隔成部分视图。

您可能还需要渲染需要放置在其中一个部分视图的标记中的部分。但是,由于部分视图不支持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 
} 
4

这是可能的剃刀帮手解决这个问题。这有点优雅,但它为我做了这份工作。

所以父视图定义一个帮手:

@helper HtmlYouWantRenderedInAPartialView() 
{ 
    <blink>Attention!</blink> 
} 

然后,当你渲染部分,你通过这个辅助函数

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

然后局部视图里面调用这个帮手像所以

<div>@ViewData.RenderHelper("OptionalSection1")</div> 

最后,你需要有这个扩展方法来简化“调用”pa RT

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

    return null; 
} 

所以整点是要通过这个帮助的委托,然后在子视图的话来说,内容呈现得到您想要的地方。

子视图的最终结果是这样的

<div><blink>Attention!</blink></div>