This post is about how to implement breadcrumbs in ASP.NET MVC Core. 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. In this post I am using a nuget package called -
To get start first create an ASP.NET Core MVC project. I am using Visual Studio. Once it is done, install the nuget package
Once it is done, we need to add the following code in the
Program.cs which will add the Breadcrumbs service to the application.
I am using the Bootstrap navigation classes for styling the breadcrumb display. Next we need to modify the
_ViewImports.cshtml file and add the
SmartBreadcrumbs tag helpers, like this.
Next we need to add the breadcrumb tag helper in the
And finally we need to set a
[DefaultBreadcrumb] attribute to the
HomeController class, like this.
Now we are ready to run the application. Once we run the application, in the Index page you will be able to see a Home link - since it is Index action under Home controller it will be disabled. And if we navigate Home link will become active. Here is the screenshot of Privacy link.
But if we like to introduce Privacy link as well in the breadcrumb you can add an attribute -
Breadcrumb to action method, like this.
And which will render like this.
If we are configuring the page Title with
ViewData["Title"] implementation, we can use the same value in the breadcrumb attribute as well, like this.
So far we implemented automatic breadcrumbs, but if we need to manipulate the values manually we can do it as well. It is useful in scenarios where we need to display breadcrumb from dynamic fields like in blogs or content management systems etc. In the action method we can programmatically create breadcrumb nodes and set it to ViewData, like this.
This will build the breadcrumb dynamically.
This way we will be able to implement breadcrumb navigation in ASP.NET Core MVC. You can find the source code in GitHub
Happy Programming :)