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

后端 未结 15 1897
渐次进展
渐次进展 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:

  • @Html.ActionLink("Home", "Index", "Home")
  • @Html.ActionLink("Disclaimer", "About", "Home")
  • 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.

提交回复
热议问题