@RenderBody、@RenderSection、@RenderPage、Html.RenderPartial、Html.RenderAction的作用和區別


1. RenderBody
在Razor引擎中沒有了“母版頁”,取而代之的是叫做“布局”的頁面(_Layout.cshtml)放在了共享視圖文件夾中。在這個頁面中,會看到標簽里有這樣一條語句:
@RenderBody()
其實它的作用和母版頁中的服務器控件類似,當創建基於此布局頁面的視圖時,視圖的內容會和布局頁面合並,而新創建視圖的內容會通過布局頁面的@RenderBody()方法呈現在標簽之間。
這個方法不需要參數,而且只能出現一次。

2. RenderPage
從名稱可以猜出來這個方法是要呈現一個頁面。比如網頁中固定的頭部可以單獨放在一個共享的視圖文件中,然后在布局頁面中通過這個方法調用,用法如下:
@RenderPage(“~/Views/Shared/_Header.cshtml”)
帶參數
@RenderPage(“~/Views/Shared/_Header.cshtml”,new{parm="my",parm2="you")
調用頁面獲取參數:
//獲取 RenderPage() 傳遞過來的參數
@PageData["param"]

3. RenderSection
布局頁面還有節(Section)的概念,也就是說,如果某個視圖模板中定義了一個節,那么可以把它單獨呈現出來,用法如下:
@RenderPage(“~/Views/Shared/_Header.cshtml”)
@RenderBody()
//模板里添加了一個節
@RenderSection(“head”)
當然還要在視圖中定義節,否則會出現異常:
@section head{
//do
}
為了防止因缺少節而出現異常,可以給RenderSection()提供第2個參數:
@RenderSection("SubMenu", false)

@if (IsSectionDefined("SubMenu"))
{
@RenderSection("SubMenu", false)
}
else
{
<p>SubMenu Section is not defined!</p>
}

4.@Html.Partial
 Partial 每次都會創建自己的 TextWriter 實例並且把內容緩存在內存中. 最后把所有 writer輸出的內容發送到一個 MvcString對象中
更多時候我們會使用 @{ Html.RenderPartial("Details"); } 而不是@Html.Partial

RenderPage()和RenderPartial()的區別

RenderPage()調用的頁面只能使用其傳遞過去的數據。
而RenderPartial()是可以使用viewdata,model等數據的。

Html.RenderPartial和Html.RenderAction的區別

Html.RenderPartial適合用在重覆使用的UserControl,並且只需要透過Model來呈現內容,或是對於廣告的UserControl也適合使用。 Html.RenderAction則會先去呼叫Controller的Action方法,如果此UserControl是需要透過資料庫取得資料來呈現(透過Action來讀取資料庫),此時會比較適合使用此方式。

5.Html.Partial("MyView")

以MvcHtmlString形式返回試圖流,遵循標准的路由規則。

Renders the "MyView" view to an MvcHtmlString. It follows the standard rules for view lookup (i.e. check current directory, then check the Shared directory).

Html.RenderPartial("MyView")

Html.Partial()類似,區別是直接輸入到頁面,不進行緩存。

Does the same as Html.Partial(), except that it writes its output directly to the response stream. This is more efficient, because the view content is not buffered in memory. However, because the method does not return any output, @Html.RenderPartial("MyView") won't work. You have to wrap the call in a code block instead: @{Html.RenderPartial("MyView");}.

RenderPage("MyView.cshtml")

返回帶路徑、文件名等的特殊視圖,同Heml.RenderPartial()一樣直接輸出,不進行緩存。可以傳遞model變量。

Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like Html.RenderPartial(). You can supply any model you like to the view by including it as a second parameter

RenderPage("MyView.cshtml",MyModel)

I prefer

@RenderPage("_LayoutHeader.cshtml")

Over

@{Html.RenderPartial("_LayoutHeader");}

Only because the syntax is easier and it is more readable. Other than that there doesn't seem to be any differences functionality wise.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM