To add a dynamic menu that expands when
hovering a mouse over the top in a ASP.NET MVC project that uses Bootstrap, make the following changes. This example will highlight
the item selected and also expands/conntracts a sub menu on a mouse-over event.
1. In _Layout.cshtml (under \Views\Shared),
add the top level menu items that you need by editing the default
items provided by visual studio in <div
class="navbar-collapse
collapse">. The code will look something
like this:
<div
class="navbar-collapse
collapse">
<ul
class="nav
navbar-nav">
<li>@Html.ActionLink("Item1",
"Index",
"Item1")</li>
<li>@Html.ActionLink("Item2",
"Index",
"Item2")</li>
<li>@Html.ActionLink("About",
"About",
"Home")</li>
<li>@Html.ActionLink("Contact",
"Contact",
"Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
2. To add the next level of menu (in this case, a menu called Item3, which has 3 sub menus), add the following code. The <span
class="caret"> will put a small triangle to indicate that this is a drop down menu. You could replace this with an image if desired.
<li
class=dropdown>
<a
class="dropdown-toggle"
data-toggle="dropdown"
href="#">Item3
<span
class="caret"></span></a>
<ul
class="dropdown-menu"
role="menu">
<li>@Html.ActionLink("SubMenuA",
"Index",
"MenuA")</li>
<li>@Html.ActionLink("SubMenuB",
"Index",
"MenuB")</li>
<li>@Html.ActionLink("SubMenuC",
"Index",
"MenuC")</li>
</ul>
</li>
3.Before the </body> tag, add this bit of JavaScript. It would be a good idea to bundle and minify this this code, particularly if it is being used for a high traffic site or it is hosted by a cloud service. See http://www.asp.net/mvc/overview/performance/bundling-and-minification for more details.
<script>
$(function
() {
$('.dropdown').hover(function
() {
$(this).addClass('open');
},
function
() {
$(this).removeClass('open');
});
});
</script>
No comments:
Post a Comment