Given a route name, can I get the default action name and controller name?
routes.MapRoute(
name: "MonthlyCalendar",
url: "FMB/Calendar/{jamaatName}/{year}/{month}",
defaults: new { controller = "FMB", action = "MonthlyCalendar",
jamaatName = UrlParameter.Optional,year = UrlParameter.Optional,
month=UrlParameter.Optional}
);
No, of course that you cannot get controller and action name from just a route name. A route mapping might look like this: {controller}/{action}/{id}
. That's the only thing you could get if you only have a route name.
If on the other hand you have a full url such as http://example.com/Home/Index
then this is an entirely different story. Now you can get the controller=Home and action=Index from the RouteData.
UPDATE:
It seems that you are attempting to extract the default values for the controller and action from your routing configuration given the route name. This can easily be done by storing the route name when registering it in the DataTokens property:
RouteTable.Routes.MapRoute(
"foo",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
).DataTokens["__RouteName"] = "foo";
and then:
var route = RouteTable.Routes.OfType<Route>().FirstOrDefault(x =>
x.DataTokens.ContainsKey("__RouteName") &&
(string)x.DataTokens["__RouteName"] == "foo"
);
if (route != null)
{
var defaultController = route.Defaults["controller"];
var defaultAction = route.Defaults["action"];
}
The reason why you need to store the route name in the DataTokens is because this information is not available in the Route instance.
UPDATE:
At some point MS added an indexer to RouteCollection
to lookup by name, so the above is no longer necessary:
((System.Web.Routing.Route)Url.RouteCollection["MyRouteName"]).Defaults
You should probably check first to make sure it exists to avoid null exception.