The MVC framework: more on links

Ok, now that codeplex is up again, I’ve already downloaded the latest bits for the ASP.NET MVC framework. In the past, we’ve already seen that there are several helpers for generating links for specific actions. As we’re going to see today, the future assemblies adds more ActionLink extension method helpers that let you specify the url of an anchor in a strongly typed manner (by using Expression<T> to define the associated action instead of relying on strings).

As you might expect, the first thing we need to do is add a reference to the future assembly in our MVC project. Then, we’ll start by adding a reference to the Microsoft.Web.Mvc namespace on the view by using the Import directive:

<%@ Import Namespace="Microsoft.Web.Mvc" %>

Now, we can start using the new ActionLink extension in the page. Here’s a quick example (supposing we’ve got a ShowMessage action method on the HomeController class that receives a string parameter called msg):

As you can see, we’re passing an Action<T> expression (where T is a controller) which ends up being parsed and transformed into a RouteValueDictionary. In this case, we’re passing a constant value to the ShowMessage. When the expression isn’t a constant, it ends up being converted into a compiled Lambda Func<Object> which is invoked. btw,here’s the HTML generated by the previous snippet:

<a href=”/Home/ShowMessage?msg=hi”>Say hi!</a>

And that’s it: by using this helper,you can build your anchors’ url in a strongly typed way. btw, and since we’re talking about additional link features introduced by the futures assembly, this post wouldn’t be complete without mentioning the BuildUrlFromExtension<T> method (an HtmlHelper extension method). The main difference (when compared with the previous method) is that this method will only return the url (instead of the complete HTML for the anchor).