LOADING STUFF...

@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.

 

原文链接:https://www.cnblogs.com/zhangpengshou/archive/2013/04/08/3007114.html
本文来源 爱码网,其版权均为 原网址 所有 与本站无关,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源。

© 版权声明

相关文章