Google analytics script

Latest jQuery CDN with code tiggling.

Thursday 17 March 2011

Removing route values from links/URLs in Asp.net MVC

I didn't really know how to properly title this post to make it easily searchable by those who bump into routing-related issue. Words like arbitrary, ambient, unwanted, unneeded, extra, unrelated etc route values popped into my mind, but I decided to title it as it is now.

One of the main pillars of Asp.net MVC is routing. Many applications can just use default route definition to cover all their scenarios but some applications require it to be a bit more complex. Look at this example:

   1:  routes.MapRoute(
   2:      "CustomerSpecific",
   3:      "Customers/{customerId}/{controller}/{action}/{id}"
   4:      new { controller = "Customers", action = "Index", id = UrlParameter.Optional },
   5:      new { customerId = @"\d+" }
   6:  );
   7:   
   8:  routes.MapRoute(
   9:      "Default",
  10:      "{controller}/{action}/{id}",
  11:      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  12:  );
Seems fine? Well it does and it works, but you will have problems when you'll be anywhere in http://www.domain.com/Customers/n/... and would like to also generate links to parts of your application that are covered by default route definition (second route). Let me show you why.