如何编写包含其他标记帮助程序的自定义 ASP.NET 5 标记帮助程序

2023-12-21

我一直在谷歌上查看 taghelpers 的示例,但找不到我正在寻找的任何示例。

我有以下代码:

<div class="form-group">
    <label asp-for="PersonName" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="PersonName" class="form-control" />
        <span asp-validation-for="PersonName" class="text-danger"></span>
    </div>
</div>

我想要做的是将其替换为类似的东西

<bootstraprow asp-for="PersonName"></bootstraprow>

但是我不确定是否编写包含其他标签帮助程序的标签帮助程序

  1. 是否可以?
  2. 如果可能的话提供上述代码示例

编辑:这与存储不同变量 https://stackoverflow.com/questions/32692857/nesting-taghelpers-in-asp-net-5-mvc-6在自定义标签帮助程序中,但我想调用其他自定义标签帮助程序或现有标签帮助程序。


如果我们检查您拥有的内容,您使用的唯一属性是 PersonName。至于标记本身,其他一切都是很好的旧式 HTML。

所以你不需要更换任何东西。你需要的是有一个依赖于的构造函数IHtmlGenerator。这将自动注入,您将能够根据您的模型生成不同的标签。

相关的IHtmlGenerator签名:

public interface IHtmlGenerator
{
    ...

    TagBuilder GenerateValidationMessage(
        ViewContext viewContext,
        string expression,
        string message,
        string tag,
        object htmlAttributes);
    TagBuilder GenerateLabel(
        ViewContext viewContext,
        ModelExplorer modelExplorer,
        string expression,
        string labelText,
        object htmlAttributes);
    TagBuilder GenerateTextBox(
        ViewContext viewContext,
        ModelExplorer modelExplorer,
        string expression,
        object value,
        string format,
        object htmlAttributes);
    ...
}

就是这样!

下面是一些捕获基本标签的代码:

[HtmlTargetElement("bootstraprow")]
public BootstrapRowTagHelper: TagHelper
{
    protected IHtmlGenerator Generator { get; set; }
    public InputTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        //todo: write your html generating code here.
    }
}

下面是一个包含示例代码的存储库,可从 TagHelpers 生成 Bootstrap HTML:

https://github.com/dpaquette/TagHelperSamples/blob/master/TagHelperSamples/src/TagHelperSamples.Bootstrap/ https://github.com/dpaquette/TagHelperSamples/blob/master/TagHelperSamples/src/TagHelperSamples.Bootstrap/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何编写包含其他标记帮助程序的自定义 ASP.NET 5 标记帮助程序 的相关文章

随机推荐