Named Routes with ASP.NET MVC

DZone 's Guide to

Named Routes with ASP.NET MVC

· ·
Free Resource
The routing engine in ASP.NET MVC is very powerful and one feature of them is the ability to use named routes.  They can help when you need to get the url of a route so that it can be accessed.  In the article on routing I posted a few weeks ago, I go over the basics and in your Global.asax.cs file you can setup your routes.  The default one looks like this:
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
If you notice, the first parameter of the MapRoute method is the route name.  Here it is set to "Default" but it could just be null if we wanted.  The name on this route doesn't really do us much good. It doesn't help us much because we still have to specify the controller and action when building an action link or using some other method to get the URL.

If I use the privacy policy example I can create a link in code by using:
<%: Html.ActionLink("Privacy Policy", "Privacy", "Home")%>
Here the ActionLink method takes three parameters: link text, action and controller in that order. This will used the default route mechanism and we will have a URL that is /Home/Privacy.  This is of course not necessarily SEO optimized so we may have a route just for the privacy policy like:
new { controller = "Home", action = "Privacy" }
In this route, the name is "Privacy", the URL will be /privacy and it will use the Home controller and Privacy action method.  I showed how you can use URL extensions to help with this, but you can also use a named route if you want to use an action link.  When using a named route, you simply create the action link with the name of the route instead of specifying the controller and action:
<%: Html.ActionLink("Privacy Policy", "Privacy") %>
The HTML link that will get created will look like this:
<a href="/privacy">Privacy Policy</a> 
As you can see it can make working with routes a bit easier.  It works very well when you have several routes that are named and you don't want to have to worry about setting the controller and action.  If you are using more dynamic routes like the default one, you may not want to use named routes and you will have to do more configuration in the action link. As with everything in development, it depends on what you are doing.  Named routes can certainly help you when working with ASP.NET MVC, but they won't be the answer every time.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}