1

I need some guidance on inserting a menu in the _layout.cshtml file. I have hit two problems: 1) Even when I create an additional model to include two data models, I am unable to pass both the models to the layout file eg:

Model:

public class IndexModel
{
    public tblMenu tblMenu { get; set; }
    public tblSite tblSite { get; set; }
}

I need info from the Menu table and the site table on the same page.

2) When I create a partial view to pass the menu data I continually get exceptions telling me that I can't use the model in this way.

My Partialview:

    @model mvcSPS.Models.IndexModel
    <li>@Model.tblMenu.MenuName</li>

My Controller:

   public ActionResult _menu()
   {
       return PartialView(db.IndexModels.ToList());
   }

My _layout.cshtml

            <ul id="navigation">
                @foreach (var item in Model)
                {
                    @Html.Partial("_menu")
                }
            </ul>

I have trawled the net and to be quite frank.. I am having a really difficult transition from ASP classic (yes I know) to ASP.net and MVC.

Your gentle guidance would be much appreciated. Thanks

Andrew

1 Answer 1

2

change your @Html.Partial in your _layout.cshtml to call the controller function and render the result of the Action method.

@foreach (var item in Model)
{
  Html.RenderAction("_menu", "Home");
}

note: you shouldn't need a prepending '@' since it's in the context of the foreach loop

EDIT: Based on my comment suggestion below

HomeController:

public ActionResult Menu() {
  return PartialView("_menu", db.IndexModels.ToList());
}

_layout.cshtml

@{Html.RenderAction("Menu", "Home");} //be sure to fully-qualify the controller since it's layout, otherwise it'll look to the current controller based on route values collection

_menu.cstml

<nav>
  <ul>
  @foreach(var item in Model) {
    Html.Partial("_menuItem", item)
  }
  </ul>
</nav>

_menuItem.cshtml

@foreach(var item in Model) {
  <li>
    <a href="http://url">text</a>
    @if(item.Children.Any())
    {
      <ul>
         Html.Partial("_menuItem", item.Children)
      </ul>
    }
  </li>
}
Sign up to request clarification or add additional context in comments.

1 Comment

although, looking back at your question, it might be more appropriate to have a second partial view that is called from your main partial view to render your nested items. I do something similar. Otherwise you'll have multiple uneeded calls back to your controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.