在MVC/Razor语法中,我试图理解为什么我们需要@RenderBody
。
例如(代码取自 example )
<html>
<head>
<meta charset="utf-8" />
<title>My WebSite</title>
<style>
#container { width: 700px; }
#left { float: left; width: 150px; }
#content { padding: 0 210px 0 160px; }
#right { float: right; width: 200px; }
.clear { clear: both; }
</style>
</head>
<body>
<div id="container">
<div id="left">
@RenderSection("left", required:false)
</div>
<div id="content">
@RenderBody()
</div>
<div id="right">
@RenderSection("right", required:false)
</div>
<div class="clear"></div>
</div>
</body>
</html>
@{
Layout = "~/_3ColLayout.cshtml";
}
<h1>Main Content</h1>
@section left {
<h1>Left Content</h1>
}
@section right {
<h1>Right Content</h1>
}
为什么我不能简单地使用 @RenderSection
来处理所有内容,如下所示:
<div id="content">
@RenderSection("Body", required:true)
</div>
@section Body{
<h1>Body Content</h1>
}
最佳答案
从@RenderBody
开始,这一点至关重要。你的 _layout 必须有它。这是您的 View 将被渲染的地方。如果你忽略它,你的应用程序将会死掉(我认为在运行时,因为 View 没有被编译)。
[更正: 如果没有 Renderbody,引用此特定布局的 View 将在运行时消亡。 (重要的是要注意布局本身是可选的。)]
部分是在 View 中定义的具有相似名称的代码块
@RenderSection(“导航栏”,必需:false)您的 View 中可能有相应的代码块。
@section Navbar{
<!-- Content Here -->
}
我强调可以,因为导航栏已被删除required: false
部分是每个 View 与 _layout 共享功能/标记的一种方式。
后续: 在我从事 MVC 开发的那段时间里,我学会了如何适度地使用节。
- 部分对于确保将 JS 引用放置在 HTML 部分中非常有用(尽管这是一种过时的做法。
- 部分对于顶部和侧面导航非常有用
- 从不需要这些部分。这样做会使您的代码变得脆弱!
关于asp.net - RenderBody 和 RenderSection 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14575225/