Asp.net-mvc – ASP.net MVC 4 loading menu from database to Partial View

asp.net-mvcasp.net-mvc-partialviewrazor

i'm an mvc newbie.

What i'm trying to do is to load menu from database and display it in partial view. This partial view will be called from _layout view.

Home Controller

in Home controller i add an action called "_MainMenu"

public class HomeController : Controller
{
        mrpDatabase _db = new mrpDatabase();

        public ActionResult _MainMenu()
        {
          return PartialView("_MainMenu", _db.menu.ToList());
        }
        ....
}

PartialView

this is my _MainMenu PartialView

@model IEnumerable<appMRP.Models.menu>
<ul id="menu">
    @foreach (var item in Model)
    {
        <li>@item.menu1</li>
    }                                            
</ul>

Layout Page

this partial menu is displayed in my _Layout.cshtml like this

<nav>                     
  @Html.Partial("_MainMenu")
</nav>

when i run this. i got error
"NullReferenceException was unhandled by user code.
Object reference not set to an instance of an object
"

seems the "Model" in my _MainMenu is null

what did i do wrong ?

thank you

Best Answer

If your partial view uses a model, you need to pass it in like this:

@Html.Partial("_MainMenu", Model.ListOfMenus)

or something to that effect. Currently, you are not specifying a model for the _MainMenu view, so null is used. When you attempt a @foreach, it throws the exception you see.

Note that @Html.Partial("_MainMenu") isn't calling your _MainMenu controller action, just rendering the view of that name.

If you want to call an action, you can use a child action like this:

@Html.Action("_MainMenu", "HomeController")