ASP.Net MVC: How can I easily change the tab color of my navigation menu based on the tab that I'm on?

↘锁芯ラ 提交于 2019-12-11 11:18:10

问题


I want to implement my navigation tabs somewhat like the ones on this site, and I've heard that this was built using ASP.Net MVC. If I'm on stackoverflow.com/users, than the "Users" menu tab is orange and all others stay grey, same if a different tab is selected.

I am pretty good with manipulating the css to change color when it's hovered or selected, etc, and adding/removing/authorizing items in the menu container, but not familiar with how to change the color of the tab based on the tab page that I'm on. Any quick and dirty way to accomplish this?


回答1:


Assign a unique id to the body element of each page (e.g. <body id="users">). In ASP.NET MVC you could have the body tag in your master page written like:

<body id="<%= ViewData["bodyId"] %>">

And in the Controller methods for each page put something like ViewData["bodyId"] = "users"; to dynamically assign the id for each page.

Then in your nav markup, assign a class with the same name on the <a> tag that links to that page:

<ul>
    <li><a href="/users" class="users">Users</a></li>
    <li><!-- more links --></li>
</ul>

Then in the css do something like this:

body#users a.users, body#another-page a.another-page {
    /* include rules for how you want the current page tab to appear */
}

That will assign your "current page" styles to any link tag with a class that matches the body tag id.




回答2:


Further to what Bryan mentioned, I usually add a "CssClass" property to my view model in cases like this. It's also useful for the situation where the calculation of the CssClass is a little complex (since it can be tested in a VM).



来源:https://stackoverflow.com/questions/1865257/asp-net-mvc-how-can-i-easily-change-the-tab-color-of-my-navigation-menu-based-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!