Html.RenderPartial in ASP.NET MVC

Just some notes on RenderPartial in ASP.NET MVC

  • If you only include the name of the partial (excluding the extension) the framework will look for the partial by
  1. Looking in the current directory (of the view that RenderPartial is being called from) and adding the extension .aspx to the partial name
  2. Looking in the current directory (of the view that RenderPartial is being called from) and adding the extension .ascx to the partial name
  3. Looking in the Views/Shared folder for the partial and adding the extension .aspx to the partial name
  4. Looking in the Views/Shared folder for the partial and adding the extension .ascx to the partial name.
  • You can’t put the extension on the end of the partial name like this as you will get an error due to the framework appending the aspx or ascx extensions to this partial name so that you end up with RenderPartial_ThisOne.ascx.aspx and RenderPartial_ThisOne.ascx.ascx, which, needless to say, is not what you would be looking for.

<% Html.RenderPartial("RenderPartial_ThisOne.ascx"); %>

  • You can pass to render partial a tilde-styled uri pointing to a partial as follows, as this is considered to be a fully qualified path to the partial. Nothing is added to the path, it is just make relative to the current application. In my opinion this is a better way to do it as it is 1. Clearer where the partial is 2. The framework doesn’t have to look in several places to find the file instead it knows exactly where it is.

<% Html.RenderPartial("~/Partials/RenderPartial_ThisOne.ascx"); %>

  • You can pass ViewData to Partials as follows.

<% Html.RenderPartial("SharedTestPartial", "This is the model Data", new ViewDataDictionary { { "MyID", 12 }}); %>

  • Remember that when ViewData is NOT passed to the Partial the Whole ViewData of the View will be passed to the Partial. (a copy of the ViewData is passed… see the next point)
  • Note that if the ViewData is edited in a partial those changes will not be reflected in the ViewData of the View that called the partial (Much like parsing a value type to a function which alters the parameter doesn’t alter the calling functions version of the variable).
Advertisements

One Response to “Html.RenderPartial in ASP.NET MVC”

  1. ASP.NET MVC Archived Blog Posts, Page 1 Says:

    […] to VoteHtml.RenderPartial in ASP.NET MVC (10/12/2009)Monday, October 12, 2009 from jwwishartJust some notes on RenderPartial in ASP.NET MVC If you only […]


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: