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>

2 comments:

  1. Thank you for sharing.
    Help me how to create a sub menu

    ReplyDelete
  2. In the event that you need to take in website architecture from home, there are a few alternatives open for you. These incorporate getting disconnected preparing through the different government or private organizations, or learning on the web by taking on the web classes and separation learning. Various elements will impact the choice you make on what preparing choice to take.
    Web Design Curriculum

    ReplyDelete