在标签助手中,如何访问标签助手属性之外的属性?

From within the tag helper, how can I access the attributes that are not properties of the tag helper?

如果我有以下标签助手:

using Microsoft.AspNetCore.Razor.TagHelpers;  

namespace CustomTagHelper.TagHelpers  
{  
    [HtmlTargetElement("my-first-tag-helper")]  
    public class MyCustomTagHelper : TagHelper  
    {  
        public string Id { get; set; }
        public string Type { get; set; }

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

            output.SuppressOutput();
            output.Content.Clear();

            output.Content.SetHtmlContent($"<input id={Id} type={Type} />");  
        }  
    }  
}  

在我传递的视图中:

<my-first-tag-helper id="my-input" type="text" placeholder="type anything you want" autocomplete="off" disabled="disabled" />

我希望能够访问 已添加到该标签的任何其他属性,这些属性不是标签助手 属性 的 ,因此我可以添加它们到输出。在此示例中,这些将是占位符、自动完成和禁用。

在前面的例子中,生成的标签应该是:

<input id="my-input" type="text" placeholder="type anything you want" autocomplete="off" disabled="disabled" />

那么,如何访问那些不是属性的属性?

我偶然发现了我自己的问题的答案。

传递给名为 Process 的方法的名为 context 的参数包含顾名思义的 属性 AllAttributes包含所有传递的属性,无论它们是否作为 属性 存在。因此,您只需过滤掉现有属性,然后创建列表中剩余的属性。

所以这就是解决方案的样子:

using Microsoft.AspNetCore.Razor.TagHelpers;  
using System.Collections.Generic;
using System.Linq;

namespace CustomTagHelper.TagHelpers  
{  
    [HtmlTargetElement("my-first-tag-helper")]  
    public class MyCustomTagHelper : TagHelper  
    {  
        public string Id { get; set; }
        public string Type { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)  
        {  
            output.SuppressOutput();
            output.Content.Clear();

            // ------------------- Begin Extra Attributes --------------------

            var attributeObjects = context.AllAttributes.ToList();

            var props = this.GetType().GetProperties().Select(p => p.Name);

            attributeObjects.RemoveAll(a => props.Contains(a.Name));

            var extraAttributeList = new List<string>();

            foreach (var attr in attributeObjects)
            {
                extraAttributeList.Add($"{attr.Name}=\"{attr.Value}\"");
            }                                                                                                 

            // ------------------- End Extra Attributes --------------------

            output.Content.SetHtmlContent($"<input id={Id} type={Type} {string.Join(" ", extraAttributeList)}/>");
        }  
    }  
}