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
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":
public enum PageRouteTable
{
// -- User Area
UserArea_Locations,
UserArea_Default,
UserArea_PasswordReset,
UserArea_Settings,
.
.
.
}
I use this enum when building the routes:
/* -- User Area Routes -- */
routes.MapPageRoute(PageRouteTable.UserArea_Default.ToString(), "home", "~/UserArea/Default.aspx");
I then created a Page extension method:
public static PageRouteTable? CurrentRoute(this Page p)
{
string[] pageRoutes = Enum.GetNames(typeof (PageRouteTable));
foreach (string pageRoute in pageRoutes)
{
if (p.RouteData.Route == RouteTable.Routes[pageRoute])
{
return (PageRouteTable)Enum.Parse(typeof (PageRouteTable), pageRoute);
}
}
return null;
}
Now in my pages I can simply use a switch to act upon it:
PageRouteTable? currentRoute = this.CurrentRoute();
if (currentRoute.HasValue) {
switch(currentRoute.Value) {
case PageRouteTable.UserArea_Default:
// Act accordingly
break;
.
.
.
}
}
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.