Making Routes Grow Up a Little
March 19th, 2008
When I saw Scott Hanselman’s first screencast tutorial on ASP.NET MVC Preview 2 I immediately asked “Where’s the named routes?” For those who don’t know, named routes is an extremely useful feature in Ruby on Rails that allows you to create a route and give it a name (if you don’t know what I’m talking about with the whole “route” thing, check out this screencast which goes over it).
The purpose of named routes is to define your URL in one place (the routes file) and give it a unique identifier (a name). Then, throughout the rest of your application you can get that URL by referencing the name, instead of typing the entire URL. Because of this, when your site structure changes (and let’s face it, it will), you only need to change the URL in one place, instead of all over your application. This is in keeping with the DRY principle (Don’t Repeat Yourself) that permeates Rails.
In response to my comment on his blog, Scott says that named routes are possible, but no amount of Googling has shown me how. Well, as any good developer does, I went ahead and figured it out for myself. So here it is, making your routes grow up by adding names.
The process is actually very simple. The name is an optional first parameter to the RoutesCollection.Add method called in your Application_Start. So we can define the following:
routes.Add("send_message", new Route("message/new/{id}", new MvcRouteHandler()));
This defines a route to the “message” controller, calls the “new” action, and passes a parameter called “id”. To access this route in your view, all you have to do is call Html.RouteLink like so:
<%= Html.RouteLink("[send a message]", "send_message") %>
and voila! You now have name routing in an ASP.NET application! It’s just getting cooler every day, isn’t it?
- Posted 5 months ago
- comments[0]
- Permalink
- Digg This!