Razor部分可以选择吗?

时间:2013-05-17 14:22:18

标签: c# asp.net-mvc asp.net-mvc-4

如果我有一个页面:

<body>
    @section SomeStuff {
        <span>This is a section I just addered</span>
    }

</body>

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

修改

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

5 个答案:

答案 0 :(得分:25)

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

@RenderSection("SomeStuff", required: false)

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

http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

答案 1 :(得分:6)

您可以通过将required参数设置为false来将节设置为可选。如果您想在您的部分中包含一些可选的包装HTML,那么您还可以使用 IsSectionDefined 方法。

@if(IsSectionDefined("SideBar"))
{
    <div class="sidebar">
        @RenderSection("SideBar", required: false)
    </div>
}

答案 2 :(得分:5)

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

@RenderSection("Somestuff", required:false)

答案 3 :(得分:0)

你可以这样做:

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

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

 @if (yourCondition) {
    <span>This is a section I just addered</span>
 }

答案 4 :(得分:0)

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

@if (someCondition)
    {
        @Html.Raw(@"
              Your stuff here
        ");
    }
相关问题