我一直关注这篇关于编写自定义Tag Helpers
here的微软文章.
我在哪里看到代码,其中元素标记在C#中被硬编码
示例(取自上面的链接)
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetHtmlContent(
$@"<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;
}
而不是这样做,有没有办法从cshtml文件加载标记模板? (类似于加载部分视图)
我的目的是拥有单独的cshtml文件(每个元素类型一个),这样我就可以轻松地设置它们的样式.我的C#看起来也很干净!
谢谢,
詹姆士
最佳答案 您可以创建局部视图,并从TagHelper类中调用它.例如:
<!-- Views/Shared/TagHelpers/MyList.cshtml -->
@model YourInfoClass
<ul>
<li><strong>Version:</strong> @Model.Version</li>
<li><strong>Copyright Year:</strong> @Model.CopyrightYear</li>
<li><strong>Approved:</strong> @Model.Approved</li>
<li><strong>Number of tags to show:</strong> @Model.TagsToShow</li>
</ul>
在你的TagHelper中:
[HtmlTargetElement("mylist")]
public class MyListTagHelper : TagHelper
{
private HtmlHelper _htmlHelper;
private HtmlEncoder _htmlEncoder;
public MyListTagHelper(IHtmlHelper htmlHelper, HtmlEncoder htmlEncoder)
{
_htmlHelper = htmlHelper as HtmlHelper;
_htmlEncoder = htmlEncoder;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.TagMode = TagMode.StartTagAndEndTag;
var partial = await _htmlHelper.PartialAsync("TagHelpers/MyList", Info);
var writer = new StringWriter();
partial.WriteTo(writer, _htmlEncoder);
output.Content.SetHtmlContent(writer.ToString());
}
}