有没有办法用Tag Helpers创建循环?

时间:2016-08-24 20:32:12

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

有没有办法创建一个Tag Helper,以某种方式迭代(像转发器一样)内部标记助手?就是这样:

AttributeError: 'tuple' object has no attribute 'split'

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

1 个答案:

答案 0 :(得分:3)

可以使用TagHelperContext.Items属性。来自doc

  

获取用于与其他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>");
    }
}