Skip to content

Managing breadcrumbs in ASP.NET core using SmartBreadcrumbs

Adding breadcrumbs to a website seems like an easy task and honestly, it should be. Unfortunately it’s not, unless you want to end up copying the almost-same code in all your pages.
Today I’ll be talking about how to add and manage breadcrumbs in an ASP.NET Core website using SmartBreadcrumbs (1.3.0), a library I created to help me add and manage breadcrumbs easily in my projects.

What are breadcrumbs and why use them?

A breadcrumb is a type of secondary navigation that shows a user’s current location in the website as well as the “history” of how he got there.
If your website has hierarchically arranged pages or is starting to have a lot of pages (e.g. e-commerce websites), Breadcrumbs can enhance the users navigation by a lot, reducing even the number of actions/clicks it takes them to do so.

Why isn’t it simple to add them in ASP.NET Core?

Adding breadcrumbs to ASP.NET Core isn’t easy because there is no out-of-the-box solution. Which leaves 2 options:

  1. Manually adding them in every page.
  2. Using an external library to do so.

Manually adding them in every page

This option shouldn’t and will not be considered because the purpose is to find a better way to handle breadcrumbs, not for us to manually add them every time.

Using an external library

This seems like a better solution, all we have to do is find THE library.
When I was making some websites for a client, I looked for a library that could help me add breadcrumbs to them without a lot of work.
I stumbled upon 2 interesting options:

  1. MvcSiteMapProviders is a tool that provides flexible menus, breadcrumb trails and SEO features for the ASP.NET MVC framework.
    As you might have noticed, it’s only for ASP.NET MVC (v3 and v4) and won’t work for ASP.NET v5 / Core.
  2. DNTBreadCrumb.Core creates custom breadcrumb definitions, based on Twitter bootstrap 3.x features for ASP.NET Core.
    I was happy when I found this library, until I tested it in my projects. DNBreadCrumb.Core works well with simple websites but not with more complex websites, because it doesn’t handle breadcrumb items coming from different Controllers (at least not out of the box, if I understood correctly), which is a downside for me since I needed that kind of navigation.

So after not finding what I was looking for, I ended up creating my own simple utility library: SmartBreadcrumbs.

About SmartBreadcrumbs

SmartBreadcrumbs - Structure

SmartBreadcrumbs is a .NET Core utility library for ASP.NET Core websites to easily add and customize breadcrumbs. It is easy to setup and even easier to use!

How it works

At initialization, SmartBreadcrumbs will create a node hierarchy using all the breadcrumb attributes used on Actions (taken from all the Controllers in your Assembly).
You’ll then be able to use a TagHelper that will check if the current action/controller has a node and will render the breadcrumb element if found.
By default, SmartBreadcrumbs uses Bootstrap 4’s classes to style the breadcrumbs.

Usage

SmartBreadcrumbs is available on Nuget, you can install it directly from the Package Manager or using the console.

Initialization

In your services configuration, add:

This will let SmartBreadcrumbs extract all the Breadcrumb attributes and their Controller.Action and create a node hierarchy of them.
If you want to customize the css classes, you can do so using the options parameter:

The SeperatorElement will be added after each node, use it when you’re using a custom theme/template for example.

Adding nodes

First, you’ll need a Default node, most of the time (if not always) this will be your Home page.
The default node will always be present as the parent, even if not explicitly chosen.

You can then start adding child nodes:

You can even use the ViewData in case you want your titles to be taken from it:

Manually setting the current nodes

In some cases, you’ll like to set the current nodes yourself. For example, you want the titles of more than one node to be taken from the database or some other source.
Luckily, SmartBreadcrumbs can trust you on this:

This is an e-commerce example where the result would be something like this: Home / Laptops / New ACER laptop

Rendering the breadcrumb

When you’re finished adding all the nodes, the last step is to make use of the TagHelper to render the breadcrumb element:

Don’t forget to import SmartBreadcrumbs:

Conclusion

Breadcrumbs can be very helpful in some situations and to be able to add and manage easily can save you a lot of work/time and keeps your code clean.
This is why I created SmartBreadcrumbs, which I now use in every project (when needed of course).

Published inProgramming

45
Leave a Reply

avatar
17 Comment threads
28 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
15 Comment authors
muhammad kamranPinkiGuest10215ElsaAmjad Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Coding Bum
Guest

Thanks for taking the time to do this. This looks like what I’ve been looking for.
I’m trying to implement this to see if it will work for me and I’m running into a error on the decorator: [Breadcrumb(“My home”, DefaultNode = true)]. The error is “The type or namespace name “DefaultNode” could not be found…”. I have “using SmartBreadcrumbs;”. What am I missing?

luis
Guest

hello the services.UseBreadcrumbs(GetType().Assembly); is crashing me the public static IWebHost BuildWebHost(string[] args) function due a null pointer, any ideas why is this?

hank
Guest
hank

Hi, I get the same error and I do not know how to solve this:

InvalidOperationException: Unable to resolve service for type ‘Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor’ while attempting to activate ‘SmartBreadcrumbs.BreadcrumbTagHelper’.

Any news on this?

Martien
Guest
Martien

Hello, I dont seem to get the manually node configuration to work. The annotation method works except for the action taking a parameter which is lost on clicking the breadcrumb. The manual node does not have a DefaultNode as parent. I upgraded to 1.4 but without succes. I tried: //[Breadcrumb(“ViewData.Title”, CacheTitle = true, FromAction = “Interaction.Index”)] public IActionResult Edit(Guid id) { var parentNode = new BreadcrumbNode(“InteractionIndex”, “Index”, “Interaction”, id, null); var editInteractionNode = new BreadcrumbNode(“ViewData.Title”, “Edit”, “Interaction”, id, parentNode); The id is the routevalue i need to pass. I get an exception in services saying “Sequence contains no matching element… Read more »

Martien
Guest
Martien

Hello,

i have this one in HomeController

[DefaultBreadcrumb(“Home”, CacheTitle = true)]
public IActionResult Index()
{
return View();
}

The Edit action in Interaction controller is in Home > Admin > Interaction > Edit

I’ll try opening an issue in GitHub.

Kind regards,
Martien

Ronan Jordan
Guest
Ronan Jordan

Hi
How do you use it in Areas. The DefaultBredcrumb is set on the homepage for users access. How do I use it in different areas, for example Admin? Setting up [Breadcrumb(“Admin”)] in Admin/Home/Index seems does not work. Root breadcrumb is still showing User/Dashboard area as default which is not what I want.

Reid S
Guest
Reid S

How can you use this tool without Bootstrap?
In other words how can we define the classes in use?

Raj
Guest
Raj

I am getting exception “Default breadcrumb attribute not found.” in services.UseBreadcrumbs(GetType().Assembly);

Any help is appreciated.

Raj
Guest
Raj

Is my issue related to this warning?

Warning NU1701 Package ‘MvcSiteMapProvider.MVC4 4.6.26’ was restored using ‘.NETFramework,Version=v4.6.1’ instead of the project target framework ‘.NETCoreApp,Version=v2.1’. This package may not be fully compatible with your project.

Raj
Guest
Raj

Please ignore this comment. It was for some other forum.

Raj
Guest
Raj

Can you please share a sample working project where you are using SmartBreadcrumbs.

lale
Guest
lale

Hello
My category is as follows
Home / Products / Details of a product
But each product can be in several categories of products.
So what kind of ID to use for the user on the product page for my product list is that the user is imported from the same category?

Category
———-
Id
Name
ParentId

Product
———–
Id
Name

ProductCategory
———————-
productid
categoryid

lale
Guest
lale

tnx
I have added a product in two categories:
1) cat1
2) cat2

On the product page, the breadcrumb is showing Home > cat1 or Home >cat2 or both?

How do I do that?

lale
Guest
lale

Yes , I see.

I need some breadcrumb in one page.but I do not know how I can do it

for example :

Home/Cat1/product1
Home/Cat2/Product1
Home/Cat3/Product1

Amjad
Guest
Amjad

Can you support .NetFramwork 4.5.1 ?

Elsa
Guest
Elsa

Does not this version work for the Mvc core 2.2?

I have an error:
‘IServiceCollection’ does not contain a definition for ‘UseBreadcrumbs’ and no accessible extension method ‘UseBreadcrumbs’ accepting a first argument of type ‘IServiceCollection’ could be found (are you missing a using directive or an assembly reference?)

Guest10215
Guest
Guest10215

Hello !
Thanks for taking the time to do this, but i have an error in my startup.cs

services.AddBreadcrumbs(Assembly.GetEntryAssembly()); Generate this :
Sequence contains more than one matching element

Idk how i can resolve it.

Any idea ?

Thank a lot

Pinki
Guest
Pinki

Works fine, except when trying to create the default node manually without the ‘DefaultBreadCrumb’.
I get this error:
InvalidOperationException: Sequence contains no matching element
System.Linq.Enumerable.Single(IEnumerable source, Func predicate)

How I try to create it manually:

var defaultNode = new MvcBreadcrumbNode(“Index”, “Home”, _localizer[“main”], false);
ViewData[“BreadcrumbNode”] = new MvcBreadcrumbNode(“CountryPage”, “Country”, countryDto.CountryName, false) { Parent = defaultNode };