2011-12-20 50 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