How to do it...

It's relatively easy to create a custom TagHelper in C# and use it inside a CSHTML view.

  1. First, let's create a VerticalMenuTagHelper class, which inherits from TagHelper. We indicate, by using the HtmlTargetElement attribute above the class, that we will use vmenu as the HTML element name to use this TagHelper in a view :
namespace R3.TagHelpers { [HtmlTargetElement("vmenu")] public class VerticalMenuTagHelper : TagHelper { public List<MenuElement> Elements { get; set; } public override void Process( TagHelperContext context, TagHelperOutput output) { output.TagName = "section"; string menuElements = "<ul>"; foreach (var e in Elements) { menuElements += $@"<li><ahref='{e.Controller}/{e.Action}'><strong>{e.Name}</strong> ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.