Sep 12, 2018

ASP.NET Core 2.1 - Extending buildin taghelpers - select

Extend existing select tag helper:

namespace Web.Infrastructure.TagHelpers
{
    [HtmlTargetElement("examcategories", Attributes = ForAttributeName)]
    public class ExamCategorySelectTagHelper : SelectTagHelper
    {
        private const string ForAttributeName = "asp-for";
        private readonly IBaseRepository _baseRepository = null;
        public ExamCategorySelectTagHelper(
            IHtmlGenerator generator,
            IBaseRepository baseRepository
            ) : base(generator)
        {
            _baseRepository = baseRepository ?? throw new ArgumentNullException(nameof(baseRepository));
        }
       
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            Items = new List<SelectListItem>()
            {
                new SelectListItem() { Text = "dummy", Value="dummy"  }
            };
            output.TagName = "select";
            await base.ProcessAsync(context, output);
        }
    }
}
Don't forget to fix your tagname to generate proper HTML select (bold above).

Register assembly with your taghelpers in _ViewImports.cshtml

Watch it! For some reason you MUST register complete assembly namespace. In my case it was:

@addTagHelper *, Web

This WON'T work:

@addTagHelper *, Web.Infrastructure.TagHelpers

Don't know why :(

Rebuild and you should have proper reference in Visual Studio autocomplete.

                <examcategories asp-for="ExamCategoryId" asp-items="ViewBag.Dummy" class="form-control"></examcategories>
Cool thing is that you can peek into production tag helper source code on GitHub:





No comments:

Post a Comment