Monday, April 2, 2012

MVC 3: Partial vs RenderPartial

Both Partial and RenderPartial methods in MVC 3 used for rendering partial views. But what is the difference between those two methods? Since asp.net mvc is opensource it is easy to check all the interesting moments right inside the framework code.

So if you download the mvc3 sources and open System.Web.Mvc project you will find PartialExtensions.cs and RenderPartialExtensions.cs:

Inside those files you will find some extensions and overloads, but all of them refer to RenderPartialInternal method, located in HtmlHelper.cs:

PartialExtensions.cs:

RenderPartialExtensions.cs:

And this is how RenderPartialInternal method signature looks like:

So the difference between Partial and RenderPartial is in the return value. Partial returns result as MvcHtmlString and uses StringWriter to render view, and RenderPartial renders the view directly with no return value.

One more thing to remember while using this two methods if you are using Razor. You can use @Html.Partial("_PartialView", Model) - and it works fine, but you can’t use @Html.RenderPartial("_PartialView", Model) - since it returns no result, and @statement syntax can be used with method, that returns some result. So in this case use RenderPartial like this: @{Html.RenderPartial("_PartialView", Model);}

1 comment :