user1857900
user1857900

Reputation: 111

MVC 4 TreeView Menu

I tried to follow this, as it was quoted as an example in many places:

http://weblogs.asp.net/mikebosch/archive/2008/11/25/hierarchical-treeview-with-asp-net-mvc-jquery.aspx

and have come up with the following (a few alterations due to me using mvc4 not 2)

In the controller class:

public ActionResult Index()
    {

        MenuDBContext db = new MenuDBContext();
        ViewData["AllMenu"] = db.Menus.ToList();
        return View(db.Menus.ToList().Where(c => c.PId == null));

    }

The view class:

@{
    ViewBag.Title = "Index";
}

@model IEnumerable<Geo.Models.Menu> 

<h2>Index</h2>

@foreach (var item in Model)
   {
      <li>
          @item
          @{var children = ViewData["AllMenu"].Where(c => c.PId == item.Id);}
          @if (children.Count() > 0)
          {
              <ul>
                    @{Html.RenderPartial("ItemControl", children);}
             </ul>

          }
     </li>
   }

I can't for the life of me work out why I can't use .Where on ViewData["AllMenu"] or .Count() on children. Any tips on where I am going wrong would be fantastic.

Upvotes: 1

Views: 3047

Answers (1)

bluetoft
bluetoft

Reputation: 5443

You need to cast ViewData["AllMenu"] as IEnumerable<

var children = (ViewData["AllMenu"] as IEnumerable<GeomantApp.Models.Menu>).Where(c => c....

ViewData is Dictionary<string,object> so when you try and get a property from that dictionary, ASP.NET has no way of knowing what it is before hand so you get compiler errors if you don't cast your object first.

Upvotes: 1

Related Questions