Adding “active” tag to navigation list in an asp.net mvc master page

后端 未结 15 1768
渐次进展
渐次进展 2020-12-12 13:31

In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:

相关标签:
15条回答
  • 2020-12-12 14:23

    Using MVC3 with a Razor View offers another option:

    _Layout.cshtml:

    <li class="@ViewBag.NavClassHome">@Html.ActionLink("Home", "Index", "Home")</li>
    <li class="@ViewBag.NavClassAbout">@Html.ActionLink("Disclaimer", "About", "Home")</li>
    

    HomeController:

    public ActionResult Index() {
        ViewBag.NavClassHome = "active";
        return View();
    } 
    
    public ActionResult About() {
        ViewBag.NavClassAbout = "active";
        return View();
    }
    

    If you want to preserve this for a postback as well, you have to assign the ViewBag value here as well:

    [HttpPost]
    public ActionResult Index() {
        ViewBag.NavClassHome = "active";
        return View();
    }
    
    [HttpPost]
    public ActionResult About() {
        ViewBag.NavClassAbout = "active";
        return View();
    }
    

    Tested and working fine for me, but you will have a css class name in your server side code.

    0 讨论(0)
  • 2020-12-12 14:25

    An old question but hopefully someone might find this very helpful.

    1. Put some thing that you can use to identify your page in the ViewBag, I used ViewgBag.PageName

    For example, in index.cshtml, put something like

    @{
        ViewBag.PageName = "Index";
    }
    
    1. Add a class to each link item with a conditional statement to return active if the page being visited has the required value, or return an empty string otherwise. View below for details:

    <li class="@((ViewBag.PageName == "Index") ? "active" : "")"><a href="@Url.Action("Index","Home")">Home</a></li>
    <li class="@((ViewBag.PageName == "About") ? "active" : "")"><a href="@Url.Action("About","Home")">About</a></li>
    <li class="@((ViewBag.PageName == "Contact") ? "active" : "")"><a href="@Url.Action("Contact","Home")">Contact</a></li>

    I didn't just test it, I use this method in my projects

    0 讨论(0)
  • 2020-12-12 14:25

    Using MVC3 with a Razor View, you can implement this like:

    <ul id="menu">
     @if (ViewContext.RouteData.Values["action"].ToString() == "Index")
     {
     <li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
     }
     else
     {
     <li>@Html.ActionLink("Home", "Index", "Home")</li>
     }
     @if (ViewContext.RouteData.Values["action"].ToString() == "About")
     {
     <li class="active">@Html.ActionLink("About", "About", "Home")</li>
     }
     else
     {
     <li>@Html.ActionLink("About", "About", "Home")</li>
     }
    </ul>
    

    And then applying your style of your ".active" class like:

    ul#menu li.active 
    {
     text-decoration:underline;
    }
    
    0 讨论(0)
提交回复
热议问题