Using MvcSitemap – for generating website breadcrumbs – Part 1

Over the last 2-3 weeks I was looking at implementing breadcrumbs on an MVC 3 website for navigation purposes and I highly recommend using the mvcsitemap provider written by Maarten Balliauw which can be found here and you can read more about his Nuget Package for it Nuget Package.

To try out the MvcSiteMap follow these steps:-

  1. Start Visual Studio and choose a new MVC 3 application.
  2. Image1

  3. Once that’s done open up the Nuget Package Manager Console and add the Nuget package called mvcsitemapprovider.
  4. Nuget

  5. Now we have added the Nuget package you will see that a file called Mvc.sitemap has been added to the root of the solution.
  6. Image3

  7. Now we want to add some content to the MVC.sitemap file, lets add some content now :-
  8. [sourcecode language=”xml”] <?xml version="1.0" encoding="utf-8" ?>
    <mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
    xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0&quot;
    xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0 MvcSiteMapSchema.xsd"
    enableLocalization="true">
    <mvcSiteMapNode title="Home" controller="Home" action="Index">
    <mvcSiteMapNode title="About" controller="Home" action="About" />
    <mvcSiteMapNode title="ContactUs" controller="ContactUs" action="Index">
    <mvcSiteMapNode title="By Phone" controller="ContactUs" action="Phone"/>
    <mvcSiteMapNode title="By Email" controller="ContactUs" action="Email"/>
    </mvcSiteMapNode>
    </mvcSiteMapNode>
    </mvcSiteMap>

    [/sourcecode]
  9. Ok so now we need to add in a ContactUsController and add the extra 2 ActionResults
  10. [sourcecode language=”csharp”] public ActionResult Phone()
    {
    return View();
    }

    public ActionResult Email()
    {
    return View();
    }
    [/sourcecode]

  11. Last but not least in order to show the breadcrumbs on a webpage just add the following code to your view
  12. [sourcecode language=”csharp”] @Html.MvcSiteMap().SiteMapPath()
    [/sourcecode]

Now we have the most basic of breadcrumbs working off of our Mvc.sitemap xml file, The next blog entry will cover more complex sitemap which uses a dynamic node provider to generate the nodes dynamically when first called – enjoy.