【问题标题】:TagHelper specify valid attributesTagHelper 指定有效属性
【发布时间】:2015-08-09 15:55:00
【问题描述】:

我正在尝试在 MVC 6 / ASP.Net vNext 中创建自定义标签助手 - 标签助手工作正常,但是有没有办法指定与标签一起使用的有效 asp- 属性,以便它们出现在intellisense? 例如,当在视图中添加符合条件的标签时,我希望 asp-ajaxasp-onsuccess 出现在 intellisense 列表中下面是我的 taghelper:

[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"]);

    }

}

用法:

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

提前致谢

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core-mvc tag-helpers


    【解决方案1】:

    使用您现在拥有的 (Attributes = AjaxForm),您将在 IntelliSense 中为 form 标签获得 asp-ajax。如果您还想在 form 标签上的 IntelliSense 中提供 data-onsuccess,您可以添加另一个 TargetElement 属性,即:[TargetElement("form", Attributes = "asp-onsuccess")]。我想指出,像这样添加Attributes 只会控制TagHelper 运行的“时间”。可以将其想象为:仅当 HTML 元素上存在这些属性时才运行。

    如果您想使用属性的值并提供 IntelliSense,您可以添加属性:

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

    这种方法不能控制TagHelper 运行的“时间”,但提供了一种将信息输入到TagHelper 的方法。它将使您能够获取它们的值并将它们添加为data- 属性。请注意,通过添加 AspAjax/AspOnSuccess 作为属性,output.Attributes 上不再存在它们的值,因此您无需删除它们。

    希望这会有所帮助!

    【讨论】:

    • 谢谢,这正好满足我的需要:)
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2016-08-19
    相关资源
    最近更新 更多