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
}