2011-12-20 48 views
32

我的問題是我似乎無法使用從嵌套模板@RenderSection@RenderSection在基本模板中定義。目前,我有一個嵌套的基本模板鏈接到一個子模板,然後在視圖頁面中使用它。當我在基本模板中定義@RenderSection並將其呈現在視圖頁面中時,會引發錯誤。@RenderSection在嵌套剃刀模板

下面是確切的問題。

我想創建一個RenderSection來允許我插入自定義腳本。 我的基本模板....

<!DOCTYPE html> 
<html> 
<head> 
<title>@ViewBag.Title</title> 
@RenderSection("HeaderContent", false) // The region of the header scripts (custom css) 

</head> 
<body> 
@RenderBody() 
</body> 
</html> 

我然後跳過子模板,因爲我不想把自定義的頭碼在那裏,它適用於網頁本身..

@section HeaderContent { 
    <script>alert("hi");</script> 
} 

我的問題是,我似乎無法將自定義頭部代碼添加到來自普通頁面的基本模板中。

下面的部分已被定義,但尚未渲染布局頁面~/Views/Shared/OneColLayer.cshtml": "HeaderContent

我是否需要在視圖頁面中包含指向基本模板的指針?

@{ 
    Layout = "~/Views/Shared/BaseTemplate.cshtml"; 
} 

我的新的基本模板

<head> 
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/layout.css")" /> 
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/global.css")" /> 
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script> 
    <script type="text/javascript" src="@Url.Content("~/js/fadeInFadeOut.js")"></script> 
    <title>@ViewBag.Title</title> 
    @RenderSection("HeaderContent", false) 
</head> 
<body> 
    @RenderBody() 
</body> 

我的新的子模板

@{ 
    Layout = "~/Views/Shared/BaseTemplate.cshtml"; 
} 
@RenderSection("HeaderContent", false) 
@RenderBody() 

我看來

@{ 
    ViewBag.Title = "Home"; 
    Layout = "~/Views/Shared/OneColLayer.cshtml"; 
} 
@section HeaderContent { 
    <h1>Left Content</h1> 
} 
<div>my view content</div> 

內容被放在現在oneCol模板的基本模板。

結果...

<div id="Content"> 
    <h1>Left Content</h1> 
</div> 

回答

50

你需要指定被允許在中間模板通過部分。

BaseTemplate.cshtml

<!DOCTYPE html> 
<html> 
    <head> 
    <title>@ViewBag.Title</title> 
    @RenderSection("HeaderContent", false) @* The region of the header scripts (custom css) *@ 
    </head> 
<body> 
    @RenderBody() 
</body> 
</html> 

編輯

新的子模板

@{ 
    Layout = "~/Views/Shared/BaseTemplate.cshtml"; 
} 
@section HeaderContent { 
    @RenderSection("HeaderContent", false) 
} 
@RenderBody() 

如果你把渲染節一節的內從基本模板,它會將該部分放在正確的位置上基本模板。


View.cshtml - >使用MiddleLayout.cshtml,因爲它的佈局

@section HeaderContent 
{ 
    <!-- header content that will now render --> 
} 

<!-- page content --> 
+0

我試圖這樣做的方法。但我的視圖中的內容顯示在它所繼承的模板上,而不是基本模板上。 – 2011-12-21 08:48:52

+0

@JamesAndrewSmith根據您的編輯,它會顯示在您的中間模板上,因爲您沒有將'@ RenderSection'放入渲染部分的中間模板中。我會編輯我的內容,告訴你你的應該是什麼樣子。 – 2011-12-21 14:58:27

+0

對我來說工作得很好 – Jacques 2012-07-30 14:25:04