为什么我的.cshtml页面需要定义内容?

Bra*_*don 11 c# razor asp.net-mvc-3

假设我的ASP.NET MVC 3应用程序中有以下结构.

  • 项目
    • Index.cshtml
  • 分类
  • 共享
    • _Index.cshtml
    • _Site.cshtml
    • Index.cshtml

这两个Index.cshtml文件都_Index.cshtml用作布局页面并_Index嵌套在_Site布局中.

Items/Index实现在中定义的可选部分_Index.Shared/Index是空的.

Items/Index视图正常工作.由于Categories没有索引,因此它使用Shared文件夹中的索引.这不起作用.

它抛出错误

尚未针对布局页面"〜/ Views/Shared/_Index.cshtml"调用"RenderBody"方法.

如果_Site调用RenderBody_Index继承_Site,内容_Index不满足所需的RenderBody调用并且Shared/Index.cshtml可以为空白?

我问的原因是因为我有一个ASP.NET MVC 1应用程序,它使用母版页实现了这个结构,并且工作正常,但是使用Razor将其转换为MVC 3导致了这个问题.

以下是我所描述的基本概要:

_Site.cshtml

<!DOCTYPE html>
// head
<body>
  @RenderBody()
</body>
Run Code Online (Sandbox Code Playgroud)

_Index.cshtml

@{
    Layout = "~/Views/Shared/_Site.cshtml";
}

<div id="sub-menu">
  // Markup
</div>

// More markup

@RenderSection("SectionOne", required: false)

@RenderSection("SectionTwo", required: false)
Run Code Online (Sandbox Code Playgroud)

Items/Index.cshtml(工作)

@{
    Layout = "~/Views/Shared/_Index.cshtml";
}

@section SectionOne {
  // Markup
}
Run Code Online (Sandbox Code Playgroud)

Shared/Index.cshtml(RenderBody错误)

@{
    Layout = "~/Views/Shared/_Index.cshtml";
}

// Rest of this file is empty
Run Code Online (Sandbox Code Playgroud)

Eri*_*sch 11

我不确定我是否完全关注你,但所有布局页面必须有一个RenderBody(),即使它们是嵌套的. RenderBody()呈现"孩子"的内容.当您具有嵌套布局页面时,嵌套布局是父级的子级,并且它的输出必须在RenderBody中呈现.同样,孩子的孩子必须将它的身体渲染到中间页面.

换句话说,任何不在@section中的东西都被认为是"身体".因此,_Index.cshtml需要渲染它的主体(Index.cshtml),而_Site.html必须渲染它的主体(_Index.cshtml).它上升了链.

编辑:

看来布局必须呈现至少一个部分,无论是a RenderBody()还是a RenderSection().虽然这些部分可能是可选的,但至少有一部分不是.在Index.cshtml中添加一个空部分或在_Index.cshtml中添加一个RenderBody().