Html.Partial and Html.RenderPartial in MVC

The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads:

public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model, ViewDataDictionary viewData);

Notice that you do not have to specify the path or file extension for a view because the logic the runtime uses to locate a partial view is the same logic the runtime uses to locate a normal view.
For example, the following code renders a partial view named AlbumDisplay. The runtime looks for the view using all the available view engines.

@Html.Partial("AlbumDisplay")

The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the response output stream instead of returning a string. For this reason, you must place RenderPartial inside a code block instead of a code expression. To illustrate, the following two lines of code render the same output to the output stream:

@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")

So, which should you use, Partial or RenderPartial? In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream, although it would require a lot of use (either high site traffic or repeated calls in a loop) before the difference would be noticeable.

Tagged . Bookmark the permalink.

Leave a Reply