Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC 4 loading menu from database to Partial View

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

like image 535
Haqi Petrucci Avatar asked Jan 15 '13 05:01

Haqi Petrucci


2 Answers

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")
like image 103
recursive Avatar answered Oct 30 '22 19:10

recursive


you already got the answer. check the _db.menu.ToList() is not returning null. I suggest you to use Model-View-ViewModel Pattern. create model for view. and return it to View, so that you can control over the model and what to show to the view .

  1. You are not passing model information to the HTML Partial method, as the results, you try to iterate over the collection. so it will throw a null reference exception.

some thing like this

 public class MenuViewModel
{
        public int menuID { get; set; }
        public string  menuname { get; set; }
        public string otherProperty { get; set; }
        public string someotherProperty { get; set; }
}

in Your View

@model IEnumerable<MenuViewModel>

<nav>                     
  @Html.Partial("_MainMenu",Model)
</nav>
like image 45
Ravi Gadag Avatar answered Oct 30 '22 18:10

Ravi Gadag