假设我的ASP.NET MVC 3应用程序中有以下结构。
两个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>
_Index.cshtml
@{
Layout = "~/Views/Shared/_Site.cshtml";
}
<div id="sub-menu">
// Markup
</div>
// More markup
@RenderSection("SectionOne", required: false)
@RenderSection("SectionTwo", required: false)
Items / Index.cshtml(Working)
@{
Layout = "~/Views/Shared/_Index.cshtml";
}
@section SectionOne {
// Markup
}
Shared / Index.cshtml(RenderBody错误)
@{
Layout = "~/Views/Shared/_Index.cshtml";
}
// Rest of this file is empty
答案 0 :(得分:11)
我不确定我是否完全关注您,但所有布局页面必须有RenderBody()
,即使它们是嵌套的。 RenderBody()
呈现“孩子”的内容。当您具有嵌套布局页面时,嵌套布局是父级的子级,并且它的输出必须在RenderBody中呈现。同样,孩子的孩子必须将它的身体渲染到中间页面。
换句话说,任何不在@section中的东西都被认为是“身体”。因此,_Index.cshtml需要渲染它的主体(Index.cshtml),而_Site.html必须渲染它的主体(_Index.cshtml)。它上升了链。
编辑:
布局似乎必须呈现至少一个部分,无论是RenderBody()
还是RenderSection()
。虽然这些部分可能是可选的,但至少有一部分不是。在Index.cshtml中添加一个空白部分,或者在_Index.cshtml中添加一个RenderBody()。