Wednesday, January 20, 2016

Add active class to HTML in ASP.Net MVC


When we use bootstrap nav-bar in asp.net MVC,  we need to dynamically update the selected item class as active. By default this feature is not available in ASP.Net Mvc. 






       <ul class="nav navbar-nav">
             <li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
             <li>@Html.ActionLink("About", "About", "Home")</li>
             <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
       </ul>



Solution :
We can achieve this by writing an extension method for ActionLink

public static class ActionHelper
    {
        public static MvcHtmlString LiActionLink(this HtmlHelper html, string text, string action, string controller)
        {
            var context = html.ViewContext;
            if (context.Controller.ControllerContext.IsChildAction)
                context = html.ViewContext.ParentActionViewContext;
            var routeValues = context.RouteData.Values;
            var currentAction = routeValues["action"].ToString();
            var currentController = routeValues["controller"].ToString();

            var str = string.Format("<li role=\"presentation\"{0}>{1}</li>",
                currentAction.Equals(action, StringComparison.InvariantCulture) &&
                currentController.Equals(controller, StringComparison.InvariantCulture)
                    ? " class=\"active\""
                    : String.Empty, html.ActionLink(text, action, controller).ToHtmlString()
                );
            return new MvcHtmlString(str);
        }
    }


We need to use the extension method as action link

 <ul class="nav navbar-nav">
                <li>@Html.LiActionLink("Home", "Index", "Home")</li>
                <li>@Html.LiActionLink("About", "About", "Home")</li>
                <li>@Html.LiActionLink("Contact", "Contact", "Home")</li>
             </ul>

No comments:

Post a Comment