MVC 3 Rendering 2-Level Menu as Partial View

7.6k Views Asked by At

I would like to implement a 2-level parent/child menu in my MVC 3 site such as

Company
 - Background
 - Contact

I have implemented a single, parent level menu as a PartialView like so ...

 <div id="menu" class="block">
    <ul id="menuItems">
        foreach (var item in Model)
        {
        <li id="@item.Id">@Html.ActionLink(item.Name, item.Action,item.Controller)</li>
        }
    </ul>
 </div>

and then included it on my MasterPage ...

 @{Html.RenderAction("MainMenu", "Menu");}

The problem is that I would like to render a second child-menu based on the menu item selected at the parent level. This involves passing the Id of the parent into the controller action that returns the menu model. I'm not sure how I can pass this parent Id into the controller action. Can anyone provide any insights into this? I'm using MVC3 & Razor.

2

There are 2 best solutions below

0
On

Looks like you're using Razor and while I'm not super familiar with that I'll take a shot at it. Basically you're going to pass a new object that has a single property of "id" to the MainMenu view. That will create another menu. Your MainMenu action should take an optional parameter of id.

public ActionResult MainMenu(int? id = null) {
  ...
}

Here is what your new list item would look like.

<li id="@item.Id">@Html.ActionLink(item.Name, item.Action,item.Controller)

@{Html.RenderAction("MainMenu", "Menu", new { id = item.Id });}

</li>
0
On

You may want to check out MvcSiteMapProvider which handles multilevel menu and sitemaps.