【发布时间】:2015-09-21 10:25:43
【问题描述】:
ASP.NET Core TagHelper documentation 给出了以下示例:
public class WebsiteContext
{
public Version Version { get; set; }
public int CopyrightYear { get; set; }
public bool Approved { get; set; }
public int TagsToShow { get; set; }
}
[TargetElement("website-information")]
public class WebsiteInformationTagHelper : TagHelper
{
public WebsiteContext Info { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetContent(
$@"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
}
这可以在你的 Razor .cshtml 中使用,如下所示:
<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1790,
Approved = true,
TagsToShow = 131 }"/>
这将生成以下 HTML:
<section>
<ul>
<li><strong>Version:</strong> 1.3</li>
<li><strong>Copyright Year:</strong> 1790</li>
<li><strong>Approved:</strong> true</li>
<li><strong>Number of tags to show:</strong> 131 </li>
</ul>
</section>
这是非常难看的标签助手语法。有没有办法嵌套另一个标签助手并获得完整的智能感知,以便网站信息的唯一允许的孩子可以是上下文?请参见下面的示例:
<website-information>
<context version="1.3" copyright="1790" approved tags-to-show="131"/>
</website-information>
在我的用例中,网站信息元素已经有很多属性,我想添加一个或多个单独的嵌套元素。
更新
我在 ASP.NET GitHub 页面上提出了this 建议,为 TagHelpers 实现此功能。
【问题讨论】:
-
为什么不将单独的参数添加到
website-information标签助手而不是单个info参数?你可以嵌套标签助手,但你不能强制只有<context>助手嵌套在<website-information>助手中 -
@DanielJ.G. 这样做有很多理由。 1.
website-information上已经有很多属性 2. 如果上下文作为子元素更符合逻辑 3. 如果context属性在逻辑上分组在一起 4. 你可以有多个context元素。
标签: asp.net razor asp.net-core asp.net-core-mvc tag-helpers