0

注册路由后,如何检索属于指定路由名称的控制器和动作名称?

例如,如果我注册这条路线:

routes.MapRoute("Category",
                "C/{id}/{urlText}",
                new { controller = "Catalog", action = "ProductListByCategoryId" }
);

我想通过路由名称参数“Category”检索控制器名称“Catalog”和操作名称“ProductListByCategoryId”。

我需要这个作为 html 助手:

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

}
4

1 回答 1

1

仅给定路线名称,您无法执行此操作。原因是一个路由可以匹配多个控制器和动作。您可以做的是从以下位置检索当前控制器和操作HttpContext

RouteData rd = HttpContext.Request.RequestContext.RouteData;
string currentController = rd.GetRequiredString("controller");
string currentAction = rd.GetRequiredString("action");
于 2012-07-07T15:32:45.210 回答