TagHelper indicates valid attributes

I'm 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 that they appear in intellisense? For example, I want asp-ajax and asp-onsuccess to appear in the intellisense list when adding a tag to a 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"]);

    }

}

      

Using:

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

      

Thank you in advance

+3


source to share


1 answer


With what you have right now ( Attributes = AjaxForm

), you'll get asp-ajax

IntelliSense in your tags for form

. If you also want to indicate data-onsuccess

in the IntelliSense tags to tags form

, you can add another attribute TargetElement

, aka: [TargetElement("form", Attributes = "asp-onsuccess")]

. I want to point out that adding Attributes

like this only controls "when" is executed TagHelper

. Think about it, for example, "Run when these attributes are present in the HTML element."

If you want to use attribute values ​​and provide IntelliSense, you can add properties:

public bool AspAjax { get; set; }

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

      



This approach does not control "when" it TagHelper

works, but provides a way to enter information into your TagHelper

. It will allow you to take your values ​​and add them as attributes data-

. Note that by adding AspAjax

/ AspOnSuccess

as properties, their values ​​no longer exist on output.Attributes

, so you don't need to remove them.

Hope this helps!

+6


source







All Articles