Search code examples
asp.net-mvc-3nullreferenceexceptionmvcsitemapproviderdisplay-templates

MvcSiteMap - NullreferenceException when iterating over the Model.Nodes. (ASP.NET MVC3 Razor)


I have some problem with MvcSiteMap. I get NullreferenceException when interating over Model.Nodes because Model is NULL.

I got it working with @Html.MvcSiteMap().Menu() but when I try the samples from your DisplayTemplate I get that NullreferenceException.

I have copy, pasted the code from the template, so I cant see why it is not working. Maybe I have forgot something ?

Heres my code:

Mvc.sitemap

<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0" enableLocalization="false" >
  <mvcSiteMapNode title="TestProject" action="Index" controller="Home" changeFrequency="Always" updatePriority="Normal">
    <mvcSiteMapNode title="Test" action="Index" controller="Home">
      <mvcSiteMapNode title="Test1_5" action="Test1_5" controller="Home">
        <mvcSiteMapNode title="Test1_4" action="Test1_4" />
        <mvcSiteMapNode title="Test1_1" action="Test1_1" />
        <mvcSiteMapNode title="Test1_6" action="Test1_6" />
        <mvcSiteMapNode title="Test1_2" action="Test1_2"/>
        <mvcSiteMapNode title="Test1_3" action="Test1_3"/>
      </mvcSiteMapNode>        
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

TestSiteMap.cshtml

@model MvcSiteMapProvider.Web.Html.Models.MenuHelperModel
@using System.Web.Mvc.Html
@using MvcSiteMapProvider.Web.Html.Models

@{
    ViewBag.Title = "TestSiteMap";
}

<h2>TestSiteMap</h2>

<ul>
    @foreach (var node in Model.Nodes)
    { 
        <li>@Html.DisplayFor(m => node) 
            @if (node.Children.Any())
            {
                @Html.DisplayFor(m => node.Children)
            }
        </li>
    }
</ul>

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

    namespace MvcApplication3.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Message = "Welcome to ASP.NET MVC!";

                return View();
            }

            public ActionResult TestSiteMap()
            {
                return View();
            }

I cant figure out what I am doing wrong!

Hope anyone can help! Thanks!


Solution

  • @Html.MvcSiteMap().Menu() will create a model and then use view template to display data. In your view, the Model is Model of you, it isn't Model of SiteMap.