Razor部分可以选择吗?

如果我有一个页面:

 @section SomeStuff { This is a section I just addered }  

布局是否有可能呈现此部分,或者与概念上的工作方式相反。 似乎能够不在页面上呈现某些部分是有用的(除非我正在考虑这个错误)。

编辑:

包含错误消息可能会有所帮助,当我将一个部分放入主页面时, 布局页面将失败: 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中我有一个名为SomeStuff的部分已定义。 这合法吗? 好像它迫使我渲染页面中的所有部分,但似乎部分应该是可选的,不是吗?

您可以指定是否需要某个部分。

 @RenderSection("SomeStuff", required: false) 

如果你没有在视图中渲染它,那么它应该不会出错,这里注明

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")) {  } 

对于某个不呈现特定部分的布局,您需要具有类似这样的布局是您的layout.cshtml

 @RenderSection("Somestuff", required:false) 

你可以这样做:

  @if (condition) { @RenderSection("SomeStuff") } 

或者直接使用conditional statement而不是@RenderSection

  @if (yourCondition) { This is a section I just addered } 

当我尝试将代码动态注入内联脚本时,我遇到了类似的问题,我通过以下方法解决了这个问题:

 @if (someCondition) { @Html.Raw(@" Your stuff here "); }