8

有什么方法可以创建一个以某种方式迭代(类似重复)内部标签助手的标签助手?也就是说,类似:

<big-ul iterateover='x'>
  <little-li value='uses x somehow'></little-li>
</bg-ul>

我知道我可以用 razor foreach 做到这一点,但试图弄清楚如何做到这一点,而不必在我的 html 中切换到 c# 代码。

4

1 回答 1

5

这是可能的,通过使用该TagHelperContext.Items属性。从文档

获取用于与其他通信的项的集合ITagHelpers。这System.Collections.Generic.IDictionary<TKey, TValue>是写时复制,以确保添加到此集合的项目仅对其他ITagHelpers目标子元素可见。

这意味着您可以将对象从父标签助手传递给它的子标签。

例如,假设您要遍历以下列表Employee

public class Employee
{
    public string Name { get; set; }
    public string LastName { get; set; }
}

在您看来,您将使用(例如):

@{ 
    var mylist = new[]
    {
        new Employee { Name = "Alexander", LastName = "Grams" },
        new Employee { Name = "Sarah", LastName = "Connor" }
    };
}
<big-ul iterateover="@mylist">
    <little-li></little-li>
</big-ul>

和两个标签助手:

[HtmlTargetElement("big-ul", Attributes = IterateOverAttr)]
public class BigULTagHelper : TagHelper
{
    private const string IterateOverAttr = "iterateover";

    [HtmlAttributeName(IterateOverAttr)]
    public IEnumerable<object> IterateOver { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "ul";
        output.TagMode = TagMode.StartTagAndEndTag;

        foreach(var item in IterateOver)
        {
            // this is the key line: we pass the list item to the child tag helper
            context.Items["item"] = item;
            output.Content.AppendHtml(await output.GetChildContentAsync(false));
        }
    }
}

[HtmlTargetElement("little-li")]
public class LittleLiTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // retrieve the item from the parent tag helper
        var item = context.Items["item"] as Employee;

        output.TagName = "li";
        output.TagMode = TagMode.StartTagAndEndTag;

        output.Content.AppendHtml($"<span>{item.Name}</span><span>{item.LastName}</span>");
    }
}
于 2017-08-18T10:35:30.250 回答