Search code examples
c#asp.net-corerazortag-helpersasp.net-core-8

How to remove a generated attribute in ASP.NET Core TagHelper?


The following input tag helper:

<input asp-for="Query.Skip" type="hidden" name="Skip" />

renders as:

<input type="hidden" name="Skip" id="Query.Skip" value="0" />

How do I make it not render the id attribute? I don't want the id attribute. I've tried id="@null", but it still renders.


Solution

  • Here's a simple override Tag Helper that removes the id attribute.

    Add a custom attribute that triggers the override Tag Helper. In the sample below, the attribute noId triggers the override.

    In the override Tag Helper, let Razor process the default output using base.Process(context, output);.

    Remove the id and custom noId attributes from the output. The end result will be:

    <input type="hidden" name="Skip" value="0" />
    

    Razor view

    @page
    @model WebApplication1.Pages.IndexModel
    @using WebApplication1.Helpers
    @addTagHelper WebApplication1.Helpers.NoIdTagHelperTagHelper, WebApplication1
    @{
    }
    <input noId asp-for="Query.Skip" type="hidden" name="Skip" />
    

    NoIdTagHelper.cs

    using Microsoft.AspNetCore.Razor.TagHelpers;
    
    namespace WebApplication1.Helpers
    {
        [HtmlTargetElement(Attributes = "noId")]
        public class NoIdTagHelperTagHelper : TagHelper
        {
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                base.Process(context, output);
                output.Attributes.Remove(output.Attributes.First(t => t.Name == "noId"));
                output.Attributes.Remove(output.Attributes.First(t => t.Name == "id"));
            }
        }
    }