When to use RenderAction vs RenderPartial with ASP.NET MVC

At first glance, RenderAction and RenderPartial both do a very similar thing – they load ‘some other content’ into the view being rendered at the place they are called. Personally, I think they should be used for different scenarios so these are my thoughts on where each one should be used and why.

First though, a quick recap on what they do:

  • RenderPartial renders a control with some model passed to it.
  • RenderAction (or RenderSubAction which addresses some issues) calls a controller action and then renders whatever view that returns with whatever model that controller action passes through it.

Hmmn, they sound pretty similar don’t they! The thing to note though is that the model passed to RenderPartial is either the current model being rendered by the calling view or a subset of it. Anything that a RenderPartial view being called is going to need has to be passed into the Model of the calling view. The view rendered using RenderAction on the other hand could contain a completely different model with no need for this to be passed in to our parent view.

Because of this, I think RenderPartial is most appropriate when what it is going to output could be considered part of the calling view but separating it out into a user control makes sense to allow re-use and avoid repeating the same rendering code in multiple views. For example, if you are rendering a person name in lots of places then instead of repeating within each view the code to output it:

<a href="<%= Url.Action("Display", "Person", new { id = Model.Person.Id}) %>">
  <%= Model.Person.Salutation %> <%= Model.Person.Forename %> <%= Model.Person.Surname %>
</a>


Instead, you move this to a separate user control such as ‘PersonName.ascx’ which expects a Person as the model:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Person>" %>
<a href="<%= Url.Action("Display", "Person", new { id = Model.Id}) %>">
    <%= Model.Salutation %> <%= Model.Forename %> <%= Model.Surname %>
</a>


Now, any place a view wants to output a persons name then you can instead call a PartialView and pass in the appropriate model:

<%= Html.RenderPartial("PersonName", Model.Person); %> 


Why would you want to do this? Well, it helps consistency and avoids repetition which makes it easy if, for example, you decide that name should not longer be in the format “Mr John Smith” but instead “Smith, John (Mr)” and you want to throw in a little jQuery magic to display a profile popup whenever anyone hovers the mouse over the name. This is a simple example but hopefully it demonstrates some benefits of using it compared to repeating the code in each view – with larger chunks of output the benefits of using RenderPartial would be even more apparent

So that is where and how I think RenderPartial should be used. How about RenderAction?

Well, I think this has it’s place when the thing that needs to be rendered isn’t the responsibility of the calling view or controller.

For example, I may have a PersonController responsible for CRUD operations on the Person class including a Display action and view but I do not want either of these to have any responsibility for anything to do with the display of Projects that the person is working on. If I want to display a list of assigned projects within the Person Display view then I would use RenderAction to add it but the responsibility and knowledge of how to do this resides with the ProjectController and it’s views. This would be called as follows:

<% Html.RenderAction("List", "Project", new {personId = Model.Person.Id}); %> 


(incidentally … note that, unlike many of the other extension methods, RenderAction doesn’t return a string so there is no ‘=’ at the beginning and a ‘;’ at the end)

Now, how the Project List is retrieved and rendered is completely the concern of the ProjectController class as it should be and the output can contain whatever it needs to display the list, provide actions to edit project entries and so on.

Another benefit of this approach is if you create different skinned versions of an app. By keeping things modular it is much easier to decide to include something in the view for one skin but not another. So, the skin (set of views) for a full desktop browser may call RenderAction to include the list in the same page whereas the skin for a mobile device friendly interface (think iPhone) would perhaps just include a link instead – both are handled by changing the view instead of changing the controllers which could otherwise be the case.

RenderSubAction alternative to RenderAction for Sub-Controllers in MVC

The ASP.NET MVC Futures assembly contains several RenderAction extension methods for HtmlHelper to allow another action to be rendered at some point within a view. Typically, this allows each controller to handle different responsibilities rather than things being combined into the parent.

So, for example, a PersonController is responsible for retrieving and assembling the model to represent a Person and pass it to the View for rendering but it should not handle Contacts – the display and CRUD operations on contacts should be handled by a ContactController and RenderAction is a convenient way to insert a list of contacts for a person into the persion display view.

So, we have a PersonController which will retrieve a Person model and pass it to the Display view. Inside this Display view, we have a call to render a list of contacts for that person:

<% Html.RenderSubAction("List", "Contact", new { personId = Model.Id }); %>

I’ve come across two problems when using this though:

1. If the parent controller action requested uses the HTTP POST method then the controller action picked up for all child actions will also be the POST version (if there is one). This is rarely the desired behavior though – I’d only expect to be sending a POST to the ContactController when I want to change something related to a contact and not when updating a person.

2. If the [ValidateInput(false)] attribute is used to allow HTML code to be posted (imagine a ‘Biography’ field on Person with a nice WYSIWYG TinyMCE Editor control …) then the request will fail unless all the child actions are automatically marked with the same attribute. I would prefer to only have to mark the methods I specifically want a POST request containing HTML input to be called.

So, I created a set of alternative RenderSubAction extension methods which address both these issues:

1. Whatever the HTTP method used for the parent action, the routing will match the GET version for child actions called.

2. The state of the [ValidateInput()] attribute will be set on all child actions called.

The code is below … just reference the namespace that you put it in within your web.config file and then change the RenderAction method to RenderSubAction – the method signatures are identical so it is a drop-in replacement.

I’d be interested in any feedback on this approach.

public static class HtmlHelperExtensions {
    public static void RenderSubAction<TController>(this HtmlHelper helper, 
Expression<Action<TController>> action) where TController : Controller { RouteValueDictionary routeValuesFromExpression = ExpressionHelper
            .GetRouteValuesFromExpression(action);
        helper.RenderRoute(routeValuesFromExpression);
    }

    public static void RenderSubAction(this HtmlHelper helper, string actionName) {
        helper.RenderSubAction(actionName, null);
    }

    public static void RenderSubAction(this HtmlHelper helper, string actionName, string controllerName) {
        helper.RenderSubAction(actionName, controllerName, null);
    }

    public static void RenderSubAction(this HtmlHelper helper, string actionName, string controllerName, 
object routeValues) { helper.RenderSubAction(actionName, controllerName, new RouteValueDictionary(routeValues)); } public static void RenderSubAction(this HtmlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues) { RouteValueDictionary dictionary = routeValues != null ? new RouteValueDictionary(routeValues)
: new RouteValueDictionary(); foreach (var pair in helper.ViewContext.RouteData.Values) { if (!dictionary.ContainsKey(pair.Key)) { dictionary.Add(pair.Key, pair.Value); } } if (!string.IsNullOrEmpty(actionName)) { dictionary["action"] = actionName; } if (!string.IsNullOrEmpty(controllerName)) { dictionary["controller"] = controllerName; } helper.RenderRoute(dictionary); } public static void RenderRoute(this HtmlHelper helper, RouteValueDictionary routeValues) { var routeData = new RouteData(); foreach (var pair in routeValues) { routeData.Values.Add(pair.Key, pair.Value); } HttpContextBase httpContext = new OverrideRequestHttpContextWrapper(HttpContext.Current); var context = new RequestContext(httpContext, routeData); bool validateRequest = helper.ViewContext.Controller.ValidateRequest; new RenderSubActionMvcHandler(context, validateRequest).ProcessRequestInternal(httpContext); } #region Nested type: RenderSubActionMvcHandler private class RenderSubActionMvcHandler : MvcHandler { private bool _validateRequest; public RenderSubActionMvcHandler(RequestContext context, bool validateRequest) : base(context) { _validateRequest = validateRequest; } protected override void AddVersionHeader(HttpContextBase httpContext) {} public void ProcessRequestInternal(HttpContextBase httpContext) { AddVersionHeader(httpContext); string requiredString = RequestContext.RouteData.GetRequiredString("controller"); IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory(); IController controller = controllerFactory.CreateController(RequestContext, requiredString); if (controller == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture,
"The IControllerFactory '{0}' did not return a controller for a controller named '{1}'.",
new object[] { controllerFactory.GetType(), requiredString })); } try { ((ControllerBase) controller).ValidateRequest = _validateRequest; controller.Execute(RequestContext); } finally { controllerFactory.ReleaseController(controller); } } } private class OverrideHttpMethodHttpRequestWrapper : HttpRequestWrapper { public OverrideHttpMethodHttpRequestWrapper(HttpRequest httpRequest) : base(httpRequest) { } public override string HttpMethod { get { return "GET"; } } } private class OverrideRequestHttpContextWrapper : HttpContextWrapper { private readonly HttpContext _httpContext; public OverrideRequestHttpContextWrapper(HttpContext httpContext) : base(httpContext) { _httpContext = httpContext; } public override HttpRequestBase Request { get { return new OverrideHttpMethodHttpRequestWrapper(_httpContext.Request); } } } #endregion }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }