Search code examples
c#asp.net-coreasp.net-core-tag-helpers

Custom TagHelper


I have created a custom Tag Helper which is setup with a new tag on the page, i.e. user-view

I use this Tag Helper in the following way

<user-view user-view-mode="Sidebar"></user-view>

and would like that this tag helper create an html structure like the following

<div class="user-view">
   [...]
</div>

However when looking at the generated code I have found

<user-view>
    <div class="user-view">
        [...]
    </div>
</user-view>

Should I use output.SetContent() instead of output.Content.AppendHtml()?

Also, the user-view-mode parameter is of type enum. Is there any way to have suggestions/hints on the html about the available values?

Last question: how do I access currently connected user in my TagHelper code?


Solution

  • As far as I know the SetContent() method also deals with the inside of the element. The way for creating TagHelpers which introduce new tags is by replacing the tag during processing. In your case this would be something like this:

    [HtmlTargetElement("user-view")]
    public class UserViewTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            // Replace user-view with div
            output.TagName = "div";
    
            // Set class
            output.Attributes.SetAttribute("class", "user-view");
    
            // Append the inner structure
            output.Content.AppendHtml(...);
        }
    }
    

    Regarding the question about accessing the currently connected user I suggest you use DI. You can inject any service (registered previously with IServiceCollection) through standard constructor injection. Additionality ViewContext and ViewComponentContext can be injected into properties thanks to dedicated attributes.

    public class UserViewTagHelper : TagHelper
    {
    
        [ViewContext]
        public ViewContext ViewContext { get; set; }
    
        [ViewComponentContext]
        public ViewComponentContext ViewComponentContext { get; set;
    }
    

    Based on those you should be able to get your user.