Computer Magic Logo
Breadcrumb

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

A lot of web sites use a breadcrumb in order to allow the visitor to see the path that has been followed in the web site. Let’s see how to create a breadcrumb.

<ul>
    @foreach (var page in CurrentPage.Ancestors().OrderBy("Level"))
    {
        <li><a href="@page.Url">@page.Name</a></li>
    }
    <li class="active">@CurrentPage.Name</li>
</ul>

We create an unordered list and we use the Ancestors() member function to get all the ancestors without including the current page. We did this because when we create a breadcrumb we want all the pages to be a link except the current page. We create a link for each of the pages that the Ancestors() member function gave us and we have a list element without link for the current page.

We have to mention that we used the OrderBy member function in order to order the pages by Level. This means that we will invert the order otherwise the order that the links will not appear in the right order.

The last thing that we have to do is to hide the breadcrumb when we are in the home page. In order to do it we check if the list returned by Ancestors() member function contains something.

@if (CurrentPage.Ancestors().Any())
{
    <ul>
        @foreach (var page in CurrentPage.Ancestors().OrderBy("Level"))
        {
            <li><a href="@page.Url">@page.Name</a></li>
        }
        <li class="active">@CurrentPage.Name</li>
    </ul>
}