微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>");
    }
}

原文地址:https://www.jb51.cc/csharp/99213.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐