Create Active/Current Menu Item In MVC3 / Razor

Add an HTML Helper:

 /// <summary>
        /// Helper to build a menu system with current/active context
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="linkText">The link text.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <returns></returns>
        public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
            string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
            if (actionName == currentAction && controllerName == currentController)
                return htmlHelper.ActionLink(
                        @class = "current"
            return htmlHelper.ActionLink(linkText, actionName, controllerName);

Add this to your master page for the navigation elements

            <div id="nav">
                <ul id="menu">                 
                    <li>@Html.MenuLink("Search", "Search", "Colleague")</li>
                    <li>@Html.MenuLink("Favorites", "Index", "Favorites")</li>

CSS to style current/active nav item

#nav ul li a.current {

One thought on “Create Active/Current Menu Item In MVC3 / Razor

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s