Way back in 2009, the MVC Futures assembly introduced “strongly-typed action helpers”. They allowed you to render links using lambda expressions pointing directly to the actions on your controller, rather than using strings:
<%= Html.ActionLink<HomeController>( c => c.Index() ) %>
Other benefits included:
- Intellisense and refactoring in Visual Studio
- Compile-time validation
- Check if user is authorized for an action (automatically hide or disable links)
Unfortunately there was a performance overhead associated with all this (http://haacked.com/archive/2009/06/02/alternative-to-expressions.aspx) that led to some interesting alternatives, including the T4MVC project.
However, there’s still hope for strongly-typed helpers. You can find an alternative implementation here that aims to resolve most of the performance concerns.
The main classes of interest are:
- ActionTemplate – Captures controller and action name from action expression. Defers getting “baked in” parameter values until (and if) needed.
- ActionBuilder – Created from ActionTemplate, captures optional parameter values. Renders links and forms (calls HtmlHelper.ActionLink or BeginForm).
Previously, most of the performance hit was from compiling the argument expressions. This version tries a few alternative approaches first, like extracting the argument value directly if it’s a ConstantExpression, and allowing named parameters in the ActionBuilder instance (if it finds a value in the parameters collection, it doesn’t bother looking at the argument part of the action expression).
Some of the features demonstrated (in HomeController.cs) include:
- Using ActionBuilders as properties of the view model. The controller defines the target actions, and the view just renders them as links.
- Using a static ActionTemplate instance to minimize the work needed to generate a list of parameterized ActionBuilders. Note the template expression simply passes ‘null’ as the argument; in this case it’ll never get used as the ActionBuilders are given their own parameter values.
- A dummy authentication mechanism to demonstrate automatically disabled links (log in with password “password” to enable the actions marked with the Authorize attribute).
You can get all the source code here