Nov 29

To use this extension download and reference MVC 2 Futures .

public static string ActionFor<TController>(this UrlHelper helper, Expression<Action<TController>> action) where TController : Controller
{
    return Microsoft.Web.Mvc.LinkBuilder.BuildUrlFromExpression(helper.RequestContext, helper.RouteCollection, action);
}

To use this extension in a view use:

Url.ActionFor<MyControllerType>(controller=>controller.MyAction())


First off I owe you all a quick update – why haven’t I blogged for over 3 months? I started at www.justgiving.com as a senior developer and well things have been a bit hectic. I now have a bank of things that I “should” blog about (that will take me until the end of the year to get through). The first post in the bank after this is an update on some of the projects I have been working on.

OK where was I? Url Helpers right, something I think that has been missing from MVC is an expression based UrlHelper. Just like the Html.DisplayFor HtmlHelper I want to be able to pass an expression rather than magic strings, for example Url.ActionFor(controller=>controller.MyAction()) instead of Url.Action(“MyController”, “MyAction”).

I did a little research on this and found a blog post by Jason Wicker where he using the LinkBuilder class in MVC 2 Futures to create a UrlHelper extension that is pretty much doing what I wanted.

Again thank you to Jason for finding this in the MVC 2 Futures library.

3 Responses to “ASP.NET MVC – Expression Based UrlHelper Extension”

  1. Paul Blamire says:

    Hi there,

    In case you haven’t seen it then It sounds like you may be interested in David Ebbo’s T4MVC as it solves the same problem you do.

    http://mvccontrib.codeplex.com/wikipage?title=T4MVC_doc&referringTitle=T4MVC

    Kind regards,

    Paul

    • DalSoft says:

      Thanks Paul, I hadn’t looked at T4MVC before and it looks great, I really like the strongly typed helper for links to content files, that would of solved some problems I have seen recently with hardcoded strings in views.

  2. John Gavin says:

    DalSoft one advantage of your code is that it is fluent
    Url.ActionFor(controller=>controller.MyAction()) rather than
    Url.ActionFor(Controller.MyAction()) when using T4MVC.

    The fluent way feels more natural as all the helpers work this way.

Leave a Reply

preload preload preload