2011-01-30 56 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>