Search code examples
asp.netasp.net-mvcasp.net-coretag-helpers

ASP.Net Core 3.1 MVC custom tag helper condition attribute is always false


I created a tag helper for select elements in my web application:

[HtmlTargetElement( "select", Attributes = nameof( AutoPostBack ) )]
    public class AutoPostBackTagHelper : TagHelper
    {
        public bool AutoPostBack { get; set; }

        public override void Process( TagHelperContext context, TagHelperOutput output )
        {
            // AutoPostBack is always false
            if ( AutoPostBack )
            {
                output.Attributes.SetAttribute( "onchange", "this.form.submit();" );
            }

            // here I could extract the attribute
            Microsoft.AspNetCore.Html.HtmlString x =
                (Microsoft.AspNetCore.Html.HtmlString)context.AllAttributes[nameof( AutoPostBack )].Value;
            // and this is working
            if ( x.Value == "true" )
            {
                output.Attributes.SetAttribute( "onchange", "this.form.submit();" );
            }
        }
    }

Here is the usage in my view:

<select asp-for="MessageType"
    asp-items="Html.GetEnumSelectList<MyViewModels.MessageType>()"
    class="form-control" AutoPostBack="true">
</select>

I want to use the condition as it is recommended through the defined attribute AutoPostBack. Why is the attribute always false?


Solution

  • In order to get AutoPostBack parameter set you need to pass it to the tag helper in 'kebab-case'.

    See the comment in this example: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-3.1#setattribute-and-setcontent

    I think if you use this it will work

    <select auto-post-back="true"></select>
    
    [HtmlTargetElement("select", Attributes = "auto-post-back")]
        public class AutoPostBackTagHelper : TagHelper
        {
            public bool AutoPostBack { get; set; }
    
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                // Will hopefully work :-)
                if (AutoPostBack)
                {
                    output.Attributes.SetAttribute("onchange", "this.form.submit();");
                }
            }
        }