I followed a few guides on creating a custom tag helper for ASP Core.
This is my helper:
using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using System; namespace ToolControlSystem.TagHelpers { [HtmlTargetElement("description", Attributes = DescriptionAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)] public class DescriptionTagHelper : TagHelper { private const string DescriptionAttributeName = "asp-for"; [HtmlAttributeName(DescriptionAttributeName)] public ModelExpression Model { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { base.Process(context, output); var description = GetDescription(Model.ModelExplorer); output.TagName = "span"; output.TagMode = TagMode.StartTagAndEndTag; output.Content.SetContent(description); } private string GetDescription(ModelExplorer modelExplorer) { string description; description = modelExplorer.Metadata.Placeholder; if (String.IsNullOrWhiteSpace(description)) { description = modelExplorer.Metadata.Description; } return description; } } }
I drop this in _ViewImports.cshtml
: @addTagHelper *, ToolConstrolSystem.TagHelpers
Annnndd... nothing. No intellisense, no tag replacing...
Any ideas?
Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.
The _ViewImports. cshtml file for an ASP.NET Core MVC app is typically placed in the Pages (or Views) folder. A _ViewImports. cshtml file can be placed within any folder, in which case it will only be applied to pages or views within that folder and its subfolders.
To create custom tag helper, the first step is to create a class that inherits from "TagHelper" class. This class has a virtual method to generate HTML tags. It contains both synchronous (Process) and asynchronous (ProcessAsync) implementation of the virtual method.
Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag helpers are a new feature and similar to HTML helpers, which help us render HTML.
You need to provide only assembly name in the view imports file.
_ViewImports.cshtml:
@addTagHelper *, ToolConstrolSystem
See Managing Tag Helper scope
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, AuthoringTagHelpers
The code above uses the wildcard syntax (*
) to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers
) will be available to every view file in the Views
directory or sub-directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With