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?
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.
FWIW, since the extensions and example shown by @Simon_Weaver are MVC-based and the post is tagged with WebForms, I thought I'd share my WebForms-based extension methods:
public static void MapPageRouteWithName(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess = true, RouteValueDictionary defaults = default(RouteValueDictionary), RouteValueDictionary constraints = default(RouteValueDictionary), RouteValueDictionary dataTokens = default(RouteValueDictionary)) { if (dataTokens == null) dataTokens = new RouteValueDictionary(); dataTokens.Add("route-name", routeName); routes.MapPageRoute(routeName, routeUrl, physicalFile, checkPhysicalUrlAccess, defaults, constraints, dataTokens); } public static string GetRouteName(this RouteData routeData) { if (routeData.DataTokens["route-name"] != null) return routeData.DataTokens["route-name"].ToString(); else return String.Empty; }
So now in Global.asax.cs when you're registering your routes, instead of doing like routes.MapPageRoute(...) - instead use the extension method and do routes.MapPageRouteWithName(...)
Then when you want to check what route you're on, simply do Page.RouteData.GetRouteName()
That's it. No reflection, and the only hard-coded references to "route-name" are in the two extension methods (which could be replaced with a const if you really wanted to).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With