I am trying to return the current dynamic View to allow me to append a css class to an ActionLink if the current View is the same as the ActionLink.

As I am passing the majority of links through a specific route, in this case Pages, the currentAction will always be Pages in most cases, despite the actual View or Template being returned from the ActionResult called.

So for example if the url is http://mytestdomain.com/sport I would like the currentAction to be Sport and not Pages.

Please see my code below:


routes.MapRoute("Pages", "{mainCategory}/{subCategory}/{pageName}", new { controller = "Home", action = "Pages", subCategory = UrlParameter.Optional, pageName = UrlParameter.Optional });


public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
    var currentController = htmlHelper.ViewContext.ParentActionViewContext.RouteData.GetRequiredString("controller");
    var currentAction = htmlHelper.ViewContext.ParentActionViewContext.RouteData.GetRequiredString("action");
    var currentView = htmlHelper.CurrentViewName();

    var builder = new TagBuilder("li")
        InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString()


    var actionSplit = actionName.TrimStart('/').Split('/');

    actionName = actionSplit[0];

    if (controllerName == currentController && actionName == currentAction)
        return new MvcHtmlString(builder.ToString().Replace("a href", "a class=\"active\" href").Replace("</li>", "").Replace("Home/", ""));

    return new MvcHtmlString(builder.ToString().Replace("</li>", "").Replace("Home/", ""));

public static string CurrentViewName(this HtmlHelper html)
        return System.IO.Path.GetFileNameWithoutExtension(((RazorView)html.ViewContext.View).ViewPath);

public ActionResult Pages(string mainCategory, string subCategory, string pageName)
    if (!string.IsNullOrEmpty(pageName))
        subCategory = subCategory + "/" + pageName;

    Page model;

    using (CMSEntities)
        model = (from f in CMSEntities.GetPage(1, mainCategory, subCategory, "Live") select f).FirstOrDefault();

    return View(model.Template, model);


@Html.MenuLink(navigation.Title, "/" + Html.ToFriendlyUrl(navigation.Title), "Home")

I have tried using var currentView = htmlHelper.CurrentViewName(); but this will always return Navigation as the ActionLink is being called from within a [ChildActionOnly] public ActionResult Navigation() for example @{ Html.RenderAction("Navigation", "Home"); } from within Views/Shared/_Layout.cshtml

Any help would be much appreciated :-)

Related posts

Recent Viewed