In this recipe, we will learn how to create a TagHelper programmatically to display a menu bar.
We create an empty web application, adding Microsoft.AspNetCore.Mvc
in project.json
. We also create a controller
class with an Index View.
It's relatively easy to create a custom TagHelper in C# and use it inside a CSHTML view.
- First, let's create a
VerticalMenuTagHelper
class, which inherits from TagHelper. We indicate, by using theHtmlTargetElement
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...