Home > Net >  How to edit a tag entry for the razor does not generate the attribute id - Asp.net Core MVC 5
How to edit a tag entry for the razor does not generate the attribute id - Asp.net Core MVC 5

Time:09-17

Razor renders the input tag by creating an html with the attributes "id", "name" and others in a predefined way, but I need to discard the "id" attribute and leave the other attributes. This needs to be done with the input, select, and textArea tags or, if possible, with all tags that generate the id attribute in html. Does anyone know how to help me?

Before Rendering:

<input type="text" asp-for="CodigoControle"  placeholder=""></input>

After Rendering:

<input type="text"  placeholder="" data-val="true" data-val-maxlength="O campo Código de Controle deve ter no máximo 15 caracteres" data-val-maxlength-max="15" id="PaisViewModel_CodigoControle" maxlength="15" name="PaisViewModel.CodigoControle" value="">

Result I need (without the id attribute):

<input type="text"  placeholder="" data-val="true" data-val-maxlength="O campo Código de Controle deve ter no máximo 15 caracteres" data-val-maxlength-max="15" maxlength="15" name="PaisViewModel.CodigoControle" value="">

Customization class:

public class CustomTagHelper : TagHelper
{        
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {

        //var attributeObjects = context.AllAttributes.ToList();
        //output.TagName = "input";
        //output.TagMode = TagMode.StartTagAndEndTag;
        
        //Remover o atributo id??????
    }
}

CodePudding user response:

This tag helper should remove the generated id attribute from input, select and textarea elements:

[HtmlTargetElement("input", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("select", Attributes = ForAttributeName)]
[HtmlTargetElement("select", Attributes = ItemsAttributeName)]
[HtmlTargetElement("textarea", Attributes = ForAttributeName)]
public class CustomTagHelper : TagHelper
{
    private const string ForAttributeName = "asp-for";
    private const string ItemsAttributeName = "asp-items";

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.Attributes.RemoveAll("id");
    }
}
  • Related