加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:42:18 所属栏目:百科 来源:网络整理
导读:有没有办法创建一个Tag Helper,以某种方式迭代(像转发器一样)内部标记助手?就是这样的: big-ul iterateover='x' little-li value='uses x somehow'/little-li/bg-ul 我知道我可以用razor foreach做到这一点但是试图找出如何做而不必在我的html中切换到c#代
有没有办法创建一个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>");
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读