Evgenyt
Evgenyt

Reputation: 10721

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

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?

Upvotes: 98

Views: 84777

Answers (6)

Julker Nien Akib
Julker Nien Akib

Reputation: 67

For ASP.NET Core 7. In the Shared folder make partial file then user this following code

<partial name="_NavBar" />

Upvotes: 0

Umar Aftab
Umar Aftab

Reputation: 535

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

Upvotes: 0

bayram
bayram

Reputation: 64

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

Upvotes: 2

Annabelle
Annabelle

Reputation: 10716

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)

Upvotes: 134

Omid Shariati
Omid Shariati

Reputation: 1916

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

Upvotes: 6

Ryan Sampson
Ryan Sampson

Reputation: 6817

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.

Upvotes: 17

Related Questions