注册路由后,如何检索属于指定路由名称的控制器和操作名称?
例如,如果我注册这条路线:
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" });
}
}
答案 0 :(得分:1)
仅给出路线名称不能这样做。原因是路由可以匹配多个控制器和操作。您可以做的是从HttpContext
:
RouteData rd = HttpContext.Request.RequestContext.RouteData;
string currentController = rd.GetRequiredString("controller");
string currentAction = rd.GetRequiredString("action");