Asp.net

RenderBody 和 RenderSection 的區別

  • January 29, 2013

MVC/Razor語法中,我試圖理解為什麼我們需要@RenderBody.

例如(程式碼取自範例

<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>
}

只是因為方便。渲染身體是你最有可能做的事情,所以最好有一個專門的功能。防止您為正文聲明 @section 並提供更容易呼叫的函式。

從 開始@RenderBody,這很重要。您的 _layout 必須擁有它。這是您的視圖將被渲染的地方。如果你忽略它,你的應用程序將會死掉(我認為在執行時,因為視圖沒有被編譯)。

[更正: 如果沒有 Renderbody,引用此特定佈局的視圖將在執行時消失。(重要的是要注意佈局本身是可選的。)]

部分是在您的視圖中定義的具有相似名稱的程式碼塊

@RenderSection(“導航欄”,必需:假)

您的視圖中可能有相應的程式碼塊。

@section Navbar{
   <!-- Content Here -->
}

我強調可能是因為導航欄已被刪除required: false

部分是每個視圖可以與 _layout 共享功能/標記的一種方式。

跟進: 在我適度的 MVC 開發時間裡,我學會了適度使用部分。

  • 節對於確保將 JS 引用放在 HTML 節中很有用(儘管這是一種過時的做法。
  • 部分對頂部和側面導航很有用
  • 從不要求章節。這樣做會使您的程式碼變得脆弱!

引用自:https://stackoverflow.com/questions/14575225