I’m trying to make a ul/li menu in my ASP.NET MVC application. The menu should have 4 to 5 top menu items and each topmenu item should have a hover/dropdown menu with some submenu items. The finished menu structure should look like a usual ul/li menu with dropdown:
<ul>
<li class="active">
<a>Topmenu 1</a>
<ul>
<li>Submenu1</li>
<li>Submenu2</li>
<li>Submenu3</li>
</ul>
</li>
<li class="inactive">
<a>Topmenu 2</a>
<ul>
<li>Submenu4</li>
<li>Submenu5</li>
<li>Submenu6</li>
</ul>
</li>
And so on...
</ul>
The top menu items should have classes with “active” and “inactive”. I solved that problem by making a custom HtmlHelper which generates the topmenu items. That looks like this:
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("tab active");
}
else {
li.AddCssClass("tab inactive");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
I call the function like this:
@Html.MenuItem("Katalog", "Index", "Katalog")
This function works very well. Unfortunately the whole topmenu <li> item is getting generated. So I have no posibility to place the <ul> for the submenuitems somewhere in the topmenu <li> tag.
Does someone have an idea how to make a menu like that? Or an idea how I can get my <ul> into the topmenu <li> tag?
You could use something like Superfish menu. I use it and it’s pretty good. The only thing you have to have is the structure of your menu somewhere in your view (
_Layout.cshtmlfor example). If you choose to go this way, just create the menu structure (<ul><li>)by hand and call the Superfish jQuery plugin. You’ll get an awesome menu ready to use no matter how many nesting levels (<ul>inside<li>) your menu may have. The plugin will handle it nicely.Sample code:
You can customize the menu with lots of options like this: