One of the most powerful features of ASP.NET MVC is its URL routing engine. The routing engine in ASP.NET MVC is used to route incoming requests to the correct controller action, but it can also generate URLs for you. This is normally done with the URL helper in views:
// Regular ASP.NET MVC: @Url.Action("View", "Blog", new { id = 123 }) // With T4MVC: @Url.Action(MVC.Blog.View(123))
This is great, as it means changing your routes will automatically update all the internal URLs throughout your site. If you're using T4MVC (which I strongly suggest), you also get compile time checking on your URLs, which means that it's literally impossible to have broken internal links (any invalid links will throw a compile error).
This is all well and good on the server side, but there's no equivalent on the client side, meaning that people often use one of these approaches:
- Hard-code URL in JavaScript directly
- Store the URL in a data attribute on the relevant element (or body)
- Create a global JavaScript object containing all the URLs the page requires (for example, Jarret Meyer's approach)
Each of these approaches has its downsides. The last one is the most promising, and I had the idea of generalising this approach and making it into a library that can be dropped into any site. There are some existing projects that tackle this problem, the main one being Zack Owens' ASP.NET MVC JavaScript Routing. Zack's library looked good but I had two issues with it:
- It's unnecessarily tightly coupled with jQuery, meaning you have to load the whole of jQuery just to use it, which is annoying if your site is just vanilla JavaScript or uses a library like PrototypeJS or MooTools instead.
- It requires you to use a custom routing syntax rather than the standard ASP.NET MVC routing
I decided to write my own library to solve this problem. My library is called RouteJs, and it is available on NuGet. It supports ASP.NET MVC 2, 3 and 4. Basically, RouteJs consists of a small piece of JavaScript to handle building URLs, as well as some information about all the routes you want to expose. All of this is served using an ASP.NET handler, so you don't need to change your build scripts or anything like that. Simply drop it into your site.
Once loaded in your site, RouteJs provides a global Router object, similar to the URL helper that comes with ASP.NET MVC. For example, the same blog view URL can be generated with the following code:
var url = Router.action('Blog', 'View', { id = 123 });
It supports most of the common features of ASP.NET MVC routing, including areas, default values and simple constraints. It does not currently support ASP.NET WebAPI, but I'll definitely add support if someone requests it.
For more information, please see the readme on Github. Please let me know what you think!
Until next time,
— Daniel