有可能通過使用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>");
}
}
我在taghelpers下找到了這篇文章的一些註釋https://blogs.msdn.microsoft.com/webdev/2015/09/02/宣佈可用性-的-ASP-淨-5-聯蛋白β7/ –