I am trying to construct a extension method which can highlight the navigation item which is currently viewed.
All my links are generated using a standard Url.RouteUrl("RouteName")
- this generates a fully qualified link for the controller and action.
Now I need to extract the controller and action from this url. Does ASP.NET MVC5 provide any features for getting that information out of a route name? Eg by asking a method with a supplied routeName
which will get me an object of the controller and action which the routeName
will point to?
I found some code on Google, which seems to work just fine. About to fine tune this snippet:
public static MvcHtmlString MenuRouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();
var route = RouteTable.Routes[routeName] as Route;
if (route != null)
{
routeValues = routeValues ?? new RouteValueDictionary();
var routeAction = (routeValues["action"] as string ?? route.Defaults["action"] as string) ?? String.Empty;
var routeController = (routeValues["controller"] as string ?? route.Defaults["controller"] as string) ?? String.Empty;
if (routeAction.Equals(currentAction, StringComparison.OrdinalIgnoreCase) && routeController.Equals(currentController, StringComparison.OrdinalIgnoreCase))
{
var currentCssClass = htmlAttributes.ContainsKey("class") ? htmlAttributes["class"] as string : String.Empty;
htmlAttributes["class"] = String.Concat(currentCssClass, !String.IsNullOrEmpty(currentCssClass) ? " " : String.Empty, "selected");
}
}
return htmlHelper.RouteLink(linkText, routeName, routeValues, htmlAttributes);
}
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.