_ViewStart.cshtml中的RenderSection()问题

Art*_*yan 12 .net asp.net-mvc razor asp.net-mvc-3

我在_Layout.cshtml中剪切了以下代码

<div id="sub-navig-container">
    @RenderSection("subNavig")
</div>

<div id="text-content">
    @RenderBody()
</div>
Run Code Online (Sandbox Code Playgroud)

当我在我的视图中添加

@section subNavig
{
    //some code
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好但是当我在_ViewStart中写这个时我有一个错误: 当前上下文中不存在名称'DefineSection' 在此输入图像描述

请解释原因,如果可能,请说明如何解决此问题

Dar*_*rov 21

_ViewStart是一个特殊视图,它源自ViewStartPage而不是从WebViewPage哪个其他视图派生而来.而且ViewStartPage班级没有DefineSection方法.因此,您无法在此文件中定义部分.您可以直接在布局中为此部分提供默认内容:

<div id="sub-navig-container">
    @if (!IsSectionDefined("subNavig"))
    {
        // some default code
    }
    else
    {
        // render the code that was overridden in the child view
        @RenderSection("subNavig")
    }
</div>
Run Code Online (Sandbox Code Playgroud)