Reputation: 3
After I register a route, how can I retrieve controller and action name what belongs to the specified route name?
For example if I register this route:
routes.MapRoute("Category",
"C/{id}/{urlText}",
new { controller = "Catalog", action = "ProductListByCategoryId" }
);
I want to retrieve the controller name "Catalog" and the action name "ProductListByCategoryId" by the route name parameter "Category".
I need this for a html helper:
public static MvcHtmlString MenuLink(this HtmlHelper helper,
string name,
string routeName,
object routeValues)
{
string currentAction = helper.ViewContext.RouteData.GetRequiredString("action");
string currentController = helper.ViewContext.RouteData.GetRequiredString("controller");
object currentId = helper.ViewContext.RouteData.Values["id"];
string actionName = ""; //This is what I want to specify
string controllerName = ""; //This is what I want to specify
var propertyInfo = routeValues.GetType().GetProperty("id");
var id = propertyInfo.GetValue(routeValues, null);
if (actionName == currentAction &&
controllerName == currentController &&
id == currentId)
{
return helper.RouteLink(name, routeName, routeValues, new { @class = "active" });
}
else
{
return helper.RouteLink(name, routeName, routeValues, new { @class = "active" });
}
}
Upvotes: 0
Views: 3032
Reputation: 1039498
You can't do this given only a route name. The reason for that is that a route could match for multiple controllers and actions. What you could do is to retrieve the current controller and action from the HttpContext
:
RouteData rd = HttpContext.Request.RequestContext.RouteData;
string currentController = rd.GetRequiredString("controller");
string currentAction = rd.GetRequiredString("action");
Upvotes: 1