Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TagHelper specify valid attributes

I am playing around with creating a custom tag helper in MVC 6 / ASP.Net vNext - the taghelper works fine, however is there a way to specify valid asp- attributes to use with the tag so they appear in intellisense? For example, I want asp-ajax and asp-onsuccess to come up in the intellisense list when adding a tag in the view that matches the criteria for my taghelper below:

[TargetElement("form", Attributes = AjaxForm)]
public class UnobtrusiveFormTagHelper : TagHelper
{
    private const string AjaxForm = "asp-ajax";

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        output.Attributes.Add("data-ajax", true);
        output.Attributes.Add("data-onsuccess", context.AllAttributes["asp-onsuccess"]);

    }

}

Usage:

<form asp-ajax="true" asp-onsuccess="dothis();">

Thanks in advance

like image 687
Carl Avatar asked Mar 16 '23 22:03

Carl


1 Answers

With what you have right now (Attributes = AjaxForm) you'll get asp-ajax in your IntelliSense for form tags. If you want to also provide data-onsuccess in IntelliSense on form tags you can add another TargetElement attribute, aka: [TargetElement("form", Attributes = "asp-onsuccess")]. I want to note, that adding Attributes like this only controls "when" the TagHelper runs. Think of it like saying: Only run when these attributes are present on the HTML element.

If you want to consume the values of the attributes AND provide IntelliSense you can add properties:

public bool AspAjax { get; set; }

[HtmlAttributeName("asp-onsuccess")]
public string AspOnSuccess { get; set; }

This approach doesn't control "when" the TagHelper runs but provides a way to input information into your TagHelper. It will enable you to take their values and add them as data- attributes. Note that by adding AspAjax/AspOnSuccess as properties their values no longer exist on output.Attributes so you don't need to remove them.

Hopefully this helps!

like image 59
N. Taylor Mullen Avatar answered Mar 23 '23 13:03

N. Taylor Mullen