I have several routes defined in my Global.asax;
When I'm on a page I need to figure out what is the route name of the current route, because route name drives my site menu.
How can this be done?
I have several routes defined in my Global.asax;
When I'm on a page I need to figure out what is the route name of the current route, because route name drives my site menu.
How can this be done?
You can add every route parameters and its not necessary this parameters be in your Url: You can put your route name as a parameter like this inGlobal.asax:
And Access it in your page:
Best way is not hard way.
If you're working with a small subset of important routes you need to check for (a special case or two) you can just do this :
A common reason for needing the route name is for debugging purposes. A quick and dirty way to do this follows - but you'll need to add each route name to the array of names. Should be fine for debugging - especially if the code isn't running during production.
For anything beyond this you should take the (minimal) time needed for @haacked's solution.
For C# you can declare your routes like so:
Then in your method where you need the route you can then call the following:
And you will have a string set in your global.asax to then use as you need.
Unfortunately, it's not possible to get the route name of the route because the name is not a property of the Route. When adding routes to the RouteTable, the name is used as an internal index for the route and it's never exposed.
There's one way to do this.
When you register a route, set a DataToken on the route with the route name and use that to filter routes.
The easiest way to do #1 is to probably write your own extension methods for mapping routes.
I would up-vote Simon_Weaver's answer but unfortunately I just joined and do not have the reputation points to do so.
Adding to his answer, because it was exactly what I was looking for, here's the way I do it:
I have a public enum "PageRouteTable":
I use this enum when building the routes:
I then created a Page extension method:
Now in my pages I can simply use a switch to act upon it:
I also have the benefit of explicitly defined variables and do not have to worry about coding against strings. This saves me a ton of headaches in maintenance.
-- happy coding.
Here's an implementation of @haacked's suggestion - with also a simple 'razor' table to display route data.
Note: You may not have realized that all the standard 'MapRoute' methods are actually extension methods. Therefore we cannot use the same name. I've just called it 'MapRoute2', because right now thats all I can think of.
You must replace all calls to MapRoute with a call to MapRoute2, don't forget all AreaRegistration files as well as global.asax.cs
Extension method:
Here's a simple razor .cshtml file I'm using to display routing information: