简体   繁体   中英

How can I retrieve the controller and action name from the route name?

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" });
    }

}

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM