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

zoa*_*oaz 5 asp.net-core-mvc tag-helpers asp.net-core

我一直在谷歌上看标签上的例子,但找不到我正在寻找的任何例子.

我有以下代码:

<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>
Run Code Online (Sandbox Code Playgroud)

我要做的是用类似的东西替换它

<bootstraprow asp-for="PersonName"></bootstraprow>
Run Code Online (Sandbox Code Playgroud)

但是,我不确定要编写包含其他标记的taghelper

  1. 可能吗?
  2. 如果可能的话,提供上面的代码示例

编辑:这与在自定义标记中存储变量不同,但我想调用其他自定义标记或现有标记.

Max*_*ler 2

If we check what you have, the only property that you are using is PersonName. As for the markup itself, everything else is good old HTML.

So you don't need to replace anything. What you need is to have constructor that has a dependency on IHtmlGenerator. This will get automatically injected and you will be able to generate the different tags based on your model.

Relevant IHtmlGenerator Signature:

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);
    ...
}
Run Code Online (Sandbox Code Playgroud)

And that's it!

Here's a bit of code that would capture the basic tag:

[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.
    }
}
Run Code Online (Sandbox Code Playgroud)

Here's a repo with sample code that generates Bootstrap HTML from TagHelpers:

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