Asp.NET Core custom Input Tag Helper rendering duplicate checkboxes
Asked Answered
O

1

6

I created a tag helper that inherits from InputTagHelper as shown by an answer in this post https://mcmap.net/q/1146081/-input-tag-helper-not-working-with-razor-code.

Here is the code

[HtmlTargetElement("input", Attributes = ForAttributeName)]
public class ExrInputTagHelper : InputTagHelper
{
    private const string ForAttributeName = "asp-for";

    [HtmlAttributeName("asp-disabled")]
    public bool IsDisabled { get; set; }

    public ExrInputTagHelper(IHtmlGenerator generator):base(generator) 
    {

    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (IsDisabled)
        {
            var d = new TagHelperAttribute("disabled", "disabled");
            output.Attributes.Add(d);
        }
        base.Process(context, output);
    }
}

This is its usage:

<input asp-for="UsingCreditCard" type="checkbox" asp-disabled="@Model.UsingACH" />

This works great but has one glaring issue. If the input type is a checkbox, it is rendered twice. All the other input types work great. Why would this be happening?

<input checked="checked" data-val="true" data-val-required="The UsingCreditCard field is required." id="UsingCreditCard" name="UsingCreditCard" type="checkbox" value="true">
<input checked="checked" id="UsingCreditCard" name="UsingCreditCard" type="checkbox" value="true">

Any thoughts are greatly appreciated.

Thanks in advance.

Occlusion answered 2/3, 2017 at 0:53 Comment(0)
A
7

In _ViewImports.cshtml, add the @removeTagHelper line. You are adding a new InputTagHelper that implements all the functionality of the old one, and both are being called.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AspNetCoreExample  // your assembly name

In InputTagHelper.cs, "checkbox" is implemented differently than all the other input types; it creates 2 input fields for a "checkbox" (both the checkbox and the backing hidden field). Since it creates it differently, it doesn't do a merge of the attributes to avoid duplicates, but creates them again.

Anthesis answered 2/3, 2017 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.