Razor: @Html.Partial() vs @RenderPage()

落爺英雄遲暮 提交于 2019-11-26 11:57:19

问题


What is the appropriate way of rendering a child template?

And what\'s the difference? Both seem to work for me.

And why does @Html.RenderPartial() no longer work?


回答1:


Html.Partial("MyView")

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")

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")

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)



回答2:


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.

EDIT: One advantage of RenderPartial is you don't have to specify the entire path or file extension it will search the common places automatically.




回答3:


The RenderPartial method doesn’t return HTML markup like most other helper methods. Instead, it writes content directly to the response stream, which is why we must call it like a complete line of C#, using a semicolon.

This is slightly more efficient than buffering the rendered HTML from the partial view, since it will be written to the response stream anyway. If you prefer a more consistent syntax, you can use the Html.Partial method, which does exactly the same as the RenderPartial method, but returns an HTML fragment and can be used as @Html.Partial("Product", p).




回答4:


We can also pass model using partial views. @Html.Partial("MyView","MyModel");




回答5:


@RenderPages() 

The above does not work in ASP.NET MVC. It only works in WebPages.

@Html.Partial("_Footer")

You will need to use the above in ASP.NET MVC.



来源:https://stackoverflow.com/questions/4501736/razor-html-partial-vs-renderpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!