Using Mvc SiteMap Provider to generate breadcrumbs for an MVC website
MvcSiteMapProvider is an open-source library for ASP.NET MVC which provides dynamic output of site structure, and is available on GitHub. The package can also be installed within your Visual Studio project directly through Nuget by targetting your required MVC Framework version:
Now the breadcrumbs can be generated and output to your site. You will notice that a file called Mvc.sitemap has been added to the root of your project, and this would contain the following for a default MVC website:
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="About" controller="Home" action="About"/>
<mvcSiteMapNode title="Contact Us" controller="Home" action="Contact"/>
New pages can be added to the structure by adding a new mvcSiteMapNode element. Each page starts wrapped by the Home node tag, and you can also wrap children of other nodes to match the structure of your website.
To output the sitemap as breadcrumbs, place the following within your view where the breadcrumbs should be output:
This will allow you to output and customize your list of breadcrumbs. The HTML which is generated for the SiteMapPath can be customized and is located under the /Views/Shared/DisplayTemplates folder. You can either edit the helpers directly, or create your own by adding a string parameter to the above SiteMapPath call.
Using with Custom Routing
If you are using custom routing, you must specify the name of the Route within each mvcSiteMapNode of the Mvc.sitemap file. Add the value for route to match the routename like route="NewRouteName" and this will match the controller when outputting the MVC Path.
Not only can the MvcSiteMapProvider package be used for breadcrumbs, but you can also use any other element to dynamically output links from your website structure. For more information on using the MVC Sitemap Provider, check out the project wiki.