Compile-Safe Links in ASP.Net MVC

One of the drawbacks of the Html.ActionLink() method is that it accepts controller and action as strings. As a consequence, there no compile-time check is performed to ensure that the referenced action is actually implemented. This also applies to Html.BeginForm(), Url.Action() and similar methods.

Recently I found an alternative extension method on SO which accepts the controller class and a controller method as parameters, rather than their names as strings:

public static MvcHtmlString ActionLink<TController>(
    this HtmlHelper htmlHelper,
    Expression<Action<TController>> expression, 
    string linkText, 
    object routeValues, 
    object htmlAttributes) where TController : Controller
    var urlHelper = 
        new UrlHelper(htmlHelper.ViewContext.RequestContext, 

    var attributes = AnonymousObjectToKeyValue(htmlAttributes);

    var link = new TagBuilder("a");

    string actionName = ExpressionHelper.GetExpressionText(expression);
    string controllerName = 
        typeof(TController).Name.Replace("Controller", "");

        urlHelper.Action(actionName, controllerName, routeValues));
    link.MergeAttributes(attributes, true);

    return new MvcHtmlString(link.ToString());

private static Dictionary<string, object> AnonymousObjectToKeyValue(
    object anonymousObject)
    var dictionary = new Dictionary<string, object>();
    if (anonymousObject == null) return dictionary;
    foreach (PropertyDescriptor propertyDescriptor in 
    return dictionary;

Personally, I prefer the single-action controller approach, as sketched here, or here, for example, where each action is implemented by a separate controller class. The meaning of the ActionLink() parameters changes such that the controllerName parameter is really a sub-namespace, and actionName is the controller class name.

Then we can simply extract the last part of the namespace and the class name of the controller class name, and pass everything else to MVC’s Html.ActionLink():

public static MvcHtmlString ActionLink<C>(this HtmlHelper htmlHelper, 
    string linkText, 
    object routeValues = null, 
    object htmlAttributes = null) where C: BaseController
    if (string.IsNullOrEmpty(linkText))
        return new MvcHtmlString("");

    var rgs = typeof(C).FullName.Split('.');
    return htmlHelper.ActionLink(linkText, 
        rgs[rgs.Length - 1].Replace("Controller", ""), 
        rgs[rgs.Length - 2], 
        routeValues, htmlAttributes);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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: