Breadcrumbs in C# MVC Website using Bootstrap

asp.net-mvc, asp.net-mvc-4, breadcrumbs, c#, twitter-bootstrap

Solution

If you want a simple solution you can use this code. It is just for default routing configuration.

Home / Controller / Page

  @if (ViewContext.RouteData.Values["controller"].ToString().ToLower() != "home")
  {
       <ol class="breadcrumb">
             <li>
              @Html.ActionLink("Home", "Index", "Home")
             </li>
             <li> @Html.ActionLink(ViewContext.RouteData.Values["controller"].ToString(), "Index")
             </li>                                
             <li class="active"> @Html.ActionLink(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["action"].ToString())
             </li>                                                       
        </ol>
   }

Problem

I'm looking to add breadcrumbs to my site, but I'm not quite sure how to go about it. I have been able to get something basic working with the following code: ``` <ol class="breadcrumb"> <li class="active"> @Html.ActionLink("Home", "Index", "Home") @if (ViewContext.RouteData.Values["controller"] != "Home" && ViewContext.RouteData.Values["action"] != "Index") { @:> @Html.ActionLink(ViewContext.RouteData.Values["controller"].ToString(), "Index", ViewContext.RouteData.Values["controller"].ToString()) } > @ViewBag.SubTitle </li> </ol> ``` The problem I have though is that this doesn't actually track your history, it just shows you ``` Home > ControllerName > CurrentItem ``` e.g. ``` Home > Members > Greg Dodd ``` This works well when you've come from a member search page, however if you come from a different page then you lose that history. How do you create a breadcrumb trail using History in MVC? I guess what I'm looking for is something like: ``` Home > Controller1 > PreviousItem > ... > CurrentItem ``` e.g. If you opened up a blog, then a particular blog item, then clicked the authors name, your breadcrumbs should be: ``` Home > Blog > SomeBlogTitle > AuthorName ``` If however you opened a list of authors and then chose a particular author, you would see the same view rendered using the same controller, but the breadcrumbs should show: ``` Home > Authors > AuthorName ```

Original source