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>

28 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
  3. Some really nice stuff on this web site , I like it. website designers nyc

    ReplyDelete
  4. great . Thanks for informations . Ill be back. Thanks again website designer nyc

    ReplyDelete
  5. The subsequent time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to read, however I really thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you possibly can repair when you werent too busy on the lookout for attention. web design agency new york

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Yay google is my king helped me to find this great web site ! . branding san francisco

    ReplyDelete
  8. This web site is usually a walk-through its the information you wished about this and didn’t know who ought to. Glimpse here, and you’ll definitely discover it. best branding agencies san francisco

    ReplyDelete
  9. Hello! Nice post! Please do keep us posted when we can see a follow up! design agencies sf

    ReplyDelete
  10. I would like to convey my admiration for your generosity in support of men and women that have the need for help with this particular concern. Your special dedication to getting the message all over had been wonderfully productive and have all the time made professionals much like me to attain their dreams. Your own invaluable tutorial means a great deal to me and additionally to my office workers. Thank you; from everyone of us. website designers san francisco

    ReplyDelete
  11. Very nice design and style and fantastic subject matter, very little else we want : D. design agency san francisco

    ReplyDelete
  12. I just added this blog to my feed reader, great stuff. Cannot get enough! web designer san francisco

    ReplyDelete
  13. You should take part in a contest for probably the greatest blogs on the web. I’ll recommend this web site! web designer san francisco

    ReplyDelete
  14. Thank you, I have recently been searching for info about this subject for ages and yours is the best I’ve found so far. web designer la

    ReplyDelete
  15. Useful info. Fortunate me I discovered your website accidentally, and I am surprised why this coincidence didn’t happened earlier! I bookmarked it. facebook marketing

    ReplyDelete
  16. those polyurethane inflatable boats are very sturdy and some are kevlar lined too but they are expensive* web designer la

    ReplyDelete
  17. there is great money involve when we talk about personal injury, attorneys make great money out of them too,, la web design

    ReplyDelete
  18. This is a great blog. and i want to visit this every day of the week ,  web designer los angeles

    ReplyDelete
  19. I think that may be an enchanting aspect, it made me assume a bit. Thank you for sparking my considering cap. Now and again I get such a lot in a rut that I just feel like a record. los angeles web agency

    ReplyDelete
  20. Admiring the time and effort you put into your website and in depth information you offer. It’s good to come across a blog every once in a while that isn’t the same out of date rehashed material. Great read! I’ve saved your site and I’m including your RSS feeds to my Google account. website design

    ReplyDelete
  21. Hello! Good stuff, please keep us posted when you post again something like that! website tips

    ReplyDelete
  22. Possible require all types of led tourdates with some other fancy car applications. Many also provide historic packs and other requires to order take into your lending center, and for a holiday in upstate New York. ??? website tips

    ReplyDelete
  23. eCommerce Website Designers who are 100% Australian developers from Website Development Australia. We build high performing eCommerce websites. ecommerce

    ReplyDelete
  24. Thanks for your insight for your fantastic posting. I’m glad I have taken the time to see this. Swiss web agency

    ReplyDelete
  25. Download All Movie Subtitles Here for Hollywood, Bollywood and all kinds of movies. Download English SRT Subtitles Here subtitleplanet.com

    ReplyDelete
  26. Thanks, foг ones marvelous posting! I genuinely enjoyed reading it, you miggһt Ƅe a great author. I wiⅼl made certain to booҝmark your blog and ѡill often come back sometime soon. I want to encoᥙrage yourself to continue your great job, have a nice evening!
    Web Development Course
    best web development courses
    web development classes
    web development course near me
    Web Development Training
    training on web development
    web development training program
    web development training course
    web development summer training

    ReplyDelete
  27. In case you're actually considering outsourcing as an alternative, consider how in your life you can supplant the cooperation you'd get from work.Professional graphic design

    ReplyDelete