MVC Blog: Add Blog Post Tag Nav


Garry West
09/11/2024

Most blogs have a list of unique blog post tag values that allows the user to do a quick filter by blog post tag. I will now add one to my index page, using the ViewComponent class.

I created a Components folder under the \Views\Shared folder:

And I create a new class, \Components\TagNavigationViewComponent.cs:

Within \Components, I create a new subfolder, TagNavigation:

Within \Components\TagNavigation, I create a default.cshtml view for my ViewComponent:

I added this registration to \Views\_ViewImports.cshtml to allow invoking my components with the vc tag helper:

And finally, I added the component, sitting to the right of the body, to \Views\Shared\_Layout.cshtml:

I want to highlight the currently selected tag. The component lives in it's own request, so I needed to add a parameter to InvokeAsync to pass the selected tag to the view:

And replace my vc tag-helper in \Views\Shared\_Layout.cshtml with the manual invoke statement:

And adjust \Shared\Components\TagNavigation\default.cshtml to highlight the correct tag:

Now we have tag navigation, just like all the other blog sites out there:

blog , mvc