Ok, here we are again for another episode on the inner workings of the MVC futures assembly. Today, we’re going to take a look at the HtmlHelper extension methods defined on the ViewExtension class. The current release of this class introduces two (static extension) methods which you can use to execute an action “in-place” during the current request:
- RenderRoute: this method lets you pass a RouteValueDictionary which is added to a RouteData object. Then, the method uses an auxiliary handler to execute the new request “in-line”;
- RenderAction/RenderAction<T>: there are several overloads of these methods. As you might expect, you’ll use them whenever you need to render a specific action of a controller. The main difference (when compared with the previous method) is that in this case you’ll end up getting two more entries on the RouteData’s Value dictionary: action and controller.
These methods end up delegating the execution of the request to a private handler: RenderActionMvcHandler. This handler expands the MvcHandler and the only thing it does is override AddVersionHeader so that it doesn’t set the custom HTTP version header. Ok, so it’s time to see this in action. Here’s a quick example that show how you can use it:
<% Html.RenderAction<HomeController>(c => c.Test()); %>
In this case, we’re rendering the Test action method of the HomeController “in-place” from within the view (yes, that call is made from within a view – not really good, right? more about it below). Do notice that the method tries to “emulate” a new request and things might not work for anything that falls out of the “simple staff” scenario. For instance, here’s a couple of things you should keep in mind if you intend to use this method:
- it goes against the “spirit” of the pattern. Using this method means that you’re calling an action from a view (and in my opinion, that is not really a good thing);
- the faked request might not have everything you might need. Since it doesn’t know (beforehand) what you need and what you want to replace you’ll get a predefined default behavior.
Ok, so now that you know that it has some short comes,you’re free to use it at your own risk :,)
And that’s all for today. Keep tuned for more on the MVC framework.