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

前端之家收集整理的这篇文章主要介绍了c# – 有没有办法用Tag Helpers创建循环?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法创建一个Tag Helper,以某种方式迭代(像转发器一样)内部标记助手?就是这样的:
<big-ul iterateover='x'>
  <little-li value='uses x somehow'></little-li>
</bg-ul>

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

解决方法

通过使用TagHelperContext.Items属性,这是可能的.从 doc

Gets the collection of items used to communicate with other ITagHelpers. This System.Collections.Generic.IDictionary<TKey,TValue> is copy-on-write in order to ensure items added to this collection are visible only to other ITagHelpers targeting child elements.

这意味着您可以将父标记助手中的对象传递给其子对象.

例如,假设您要迭代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>");
    }
}

猜你在找的C#相关文章