How can dynamic breadcrumbs be achieved with ASP.net MVC?

Ronnie Overby picture Ronnie Overby · Jul 1, 2009 · Viewed 84.8k times · Source

How can dynamic breadcrumbs be achieved with ASP.net MVC?

If you are curious about what breadcrumbs are:

What are breadcrumbs? Well, if you have ever browsed an online store or read posts in a forum, you have likely encountered breadcrumbs. They provide an easy way to see where you are on a site. Sites like Craigslist use breadcrumbs to describe the user's location. Above the listings on each page is something that looks like this:

s.f. bayarea craigslist > city of san francisco > bicycles

EDIT

I realize what is possible with the SiteMapProvider. I am also aware of the providers out there on the net that will let you map sitenodes to controllers and actions.

But, what about when you want a breadcrumb's text to match some dynamic value, like this:

Home > Products > Cars > Toyota

Home > Products > Cars > Chevy

Home > Products > Execution Equipment > Electric Chair

Home > Products > Execution Equipment > Gallows

... where the product categories and the products are records from a database. Some links should be defined statically (Home for sure).

I am trying to figure out how to do this, but I'm sure someone has already done this with ASP.net MVC.

Answer

Sean Haddy picture Sean Haddy · Nov 27, 2013

Sitemap's are definitely one way to go... alternatively, you can write one yourself! (of course as long as standard MVC rules are followed)... I just wrote one, I figured I would share here.

@Html.ActionLink("Home", "Index", "Home")
@if(ViewContext.RouteData.Values["controller"].ToString() != "Home") {
    @:> @Html.ActionLink(ViewContext.RouteData.Values["controller"].ToString(), "Index", ViewContext.RouteData.Values["controller"].ToString()) 
}
@if(ViewContext.RouteData.Values["action"].ToString() != "Index"){
    @:> @Html.ActionLink(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString()) 
}

Hopefully someone will find this helpful, this is exactly what I was looking for when I searched SO for MVC breadcrumbs.