Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Add active class to layout bootstrap navbar in MVC

How to add an active class to my bootstrap navbar in MVC with?

Hers is code example,

Whenever nav links clicked "navHelperExtension" class MakeActiveClass method adds active class to nav list item.

<ul id="topMenu" class="navbar-nav">
<li id="navHome" class="@navHelperExtension.MakeActiveClass("Index", "Home")">
<a id="acHome" class="nav-link" href="@Url.Action("Index", "Home")">Home </a>
<li id="navAbout" class="@navHelperExtension.MakeActiveClass("About","Home")">
<a id="acAbout" class="nav-link" href="@Url.Action("About", "Home")">About us </a>
<li id="navTeam" class="@navHelperExtension.MakeActiveClass("Team","Details")">
<a id="acTeam" class="nav-link" href="@Url.Action("Team", "Details")">Our Team</a>
<li id="navContact" class="@navHelperExtension.MakeActiveClass("Contact","Details")">
<a id="acContact" class="nav-link" href="@Url.Action("Contact", "Details")">Contact </a>

C# static class and method to make current selected controller link active

public static class
  public static string MakeActiveClass(string controller)
            System.Web.Mvc.UrlHelper urlHelper= ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Url;
            string result = "nav-item active";
       string controllerName =urlHelper.RequestContext.RouteData.Values["controller"].ToString();
            if (!controllerName.Equals(controller, StringComparison.OrdinalIgnoreCase))
                result = "nav-item";
            return result;

View without layout in MVC

If you want to show view without any surrounding _Layout page, you can set Layout=null.

Code sample,

With following custom error view, you displayed without surrounding _Layout page.

    Layout = null;
<div class="alert alert-danger alert-dismissible fade show">
        <h5>Error! </h5>
        <h6>Something went wrong, contact admin, or try again</h6>