Smart Bread crumbs in ASP.NET Core
This post is about how to implement Smartbreadcrumbs in ASP.NET MVC Core. Smartbreadcrumbs is a very popular Breadcrumbs implementation library for ASP.Net core websites. Breadcrumbs refers to web-based navigation which allows users to keep track of their current location on a website.
Let’s start first with the installation of the SmartBreadcrumbs library in the ASP.NET core framework.
Note: Following example is based on the .NET core 2.2 version.
Step 1: Install Smartbreadcrumbs via NuGet Package Manager. If you want to use NuGet, just search for “Smartbreadcrumbs” or run the following command in the NuGet Package Manager console:
PM> Install-Package SmartBreadcrumbs -Version 2.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
Step 2: Once the installation is done, we need to add the following line of code in the startup.cs file.
services.AddBreadcrumbs(Assembly.GetExecutingAssembly(), options =>
{
options.TagName = "nav";
options.TagClasses = "";
options.OlClasses = "breadcrumb";
options.LiClasses = "breadcrumb-item";
options.ActiveLiClasses = "breadcrumb-item active";
options.SeparatorElement = "<li class=\"separator\">/</li>";
});
The SeperatorElement will be added after each node, use it when you’re using a custom theme/template for example.
Step 3: We are going to add smarbreadcrumbs tag helper on the _ViewImports.cshtml file under the View folder.
@addTagHelper *, SmartBreadcrumbs
Now if you want to show breadcrumbs on all pages then add in _Layout.cshml or you can also add on a specific page as well.
Step 4: Add the following line of code to show breadcrumbs on DOM.
<breadcrumb></breadcrumb>
In my case, I added in specific page:
@model BlogModel
<breadcrumb></breadcrumb>
<div class="project-wrapper">
<div class="row">
Finally, we need to add [DefaultBreadcrumb] attribute to the Controller class, like below:
namespace ShareCode.Web.Controllers {
[DefaultBreadcrumb]
public class BlogController : Controller
{
However, if we need to display breadcrumbs 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.
public ActionResult Details(string url)
{
BlogModel blogModel =_blogRepository.GetBlogsByQuery().Where(s => s.BlogUrl ==url).FirstOrDefault();
blogModel.BlogList = new List<BlogModel>();
blogModel.BlogList =_blogRepository.GetBlogsByQuery().Take(3).ToList();
var articlesPage = new MvcBreadcrumbNode("Index", "Home", "Blog");
var articlePage = new MvcBreadcrumbNode("Details", "Blog",blogModel.Name) { Parent = articlesPage };
ViewData["BreadcrumbNode"] = articlePage;
ViewData["Title"] = blogModel.BlogUrl;
return View(blogModel);
}
Above line of code create the breadcrumb dynamically.