sir*_*lot 13 c# asp.net-mvc asp.net-mvc-4
如果我有一个页面:
<body>
@section SomeStuff {
<span>This is a section I just addered</span>
}
</body>
Run Code Online (Sandbox Code Playgroud)
布局是否有可能不呈现此部分,或者与概念上的工作方式相反.似乎能够不在页面上呈现某些部分是有用的(除非我正在考虑这个错误).
编辑:
包括错误信息可能会有所帮助,当我把一个部分进入主网页,在布局网页失败:The following sections have been defined but have not been rendered for the layout page "/Views/Layouts/_Layout1.cshtml": "SomeStuff".因为如果它迫使我来渲染页面或某事上的每个部分.
换句话说,在Layout.cshtml中,我不调用@RenderSection,但在Index.html中我有一个名为SomeStuffdefined 的部分.这合法吗?好像它迫使我渲染页面中的所有部分,但看起来部分应该是可选的,不是吗?
Sli*_*sim 25
您可以指定是否需要某个部分.
@RenderSection("SomeStuff", required: false)
Run Code Online (Sandbox Code Playgroud)
如果你没有在视图中渲染它,那么它应该不会出错,这里注意到了
http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
您可以通过将required参数设置为false来将节设置为可选节.如果您想在您的部分中包含一些可选的包装器HTML,那么您也可以使用IsSectionDefined方法.
@if(IsSectionDefined("SideBar"))
{
<div class="sidebar">
@RenderSection("SideBar", required: false)
</div>
}
Run Code Online (Sandbox Code Playgroud)
对于某个不呈现特定部分的布局,您需要具有类似这样的布局是您的layout.cshtml
@RenderSection("Somestuff", required:false)
Run Code Online (Sandbox Code Playgroud)