TagHelper(标签助手)是ASP.NET Core非常好的一种新特性。可以扩展视图,让其看起来像一个原生HTML标签。
应该使用TagHelper替换HtmlHelper,因其更简洁更易用,且支持依赖注入。可以通过其构造函数中注入所需要的服务。
一、扩展的标签:
下面使用一个简单的标签示例扩展:
[HtmlTargetElement("hello")]
public class HelloTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "p";
output.Attributes.Add("id", context.UniqueId);
output.Attributes.Add("style", "color:red;font-weight:bold;");
output.PreContent.SetContent("Hello ");
output.PostContent.SetContent($", time is now: {DateTime.Now.ToString("HH:mm:")}");
}
}
在此定义了一个“hello”标签,可以像其他标识一样使用。
不过前提得先将该标签所在的命名空间引用到到cshtml文件中(此处使用"_ViewImports.cshtml"进行设置)
@addTagHelper "*, TagAbout"
在View中使用,如在Index.cshtml中使用,如下:
<div class="col-md-3">
<hello>Jackie Lee</hello>
</div>
运行效果:
产生的HTML如下:
二、扩展的标签属性:
定义a、p、ul、li、button、span、div标签的属性扩展TagHelper类如下,为其内容最后添加一段通过依赖注入进来的类调用返回的内容。
并为其添加title属性,以提示“author-for"所设置的内容:
[HtmlTargetElement("a", Attributes = ForAttributeName)]
[HtmlTargetElement("p", Attributes = ForAttributeName)]
[HtmlTargetElement("ul", Attributes = ForAttributeName)]
[HtmlTargetElement("li", Attributes = ForAttributeName)]
[HtmlTargetElement("button", Attributes = ForAttributeName)]
[HtmlTargetElement("span", Attributes = ForAttributeName)]
[HtmlTargetElement("div", Attributes = ForAttributeName)]
public class AuthorTagHelper : TagHelper
{
private const string ForAttributeName = "author-for";
private const string TextAttributeName = "content"; [HtmlAttributeName(ForAttributeName)]
public string AuthorFor { get; set; } private ContentManager _contentManager; public AuthorTagHelper(ContentManager contentManager)
{
_contentManager = contentManager;
} public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.Add("title", AuthorFor);
output.PostContent.AppendHtml($"<span style='font-weight:bold;color:orange;'>[{_contentManager.GetContent()}]</span>");
// 可用于验证
if (false)
{
var builder = output.Content;
output.SuppressOutput(); // nothing to output
builder.AppendHtml(string.Empty);
}
}
}
依赖注入的类:
public class ContentManager
{
public static ContentManager ContentMgr { get; private set; } = new ContentManager();
public string GetContent()
{
return $"Well, this is the injected data by the tag helper.";
}
}
在Startup的ConfigureServices中添加依赖注入对象:
services.AddSingleton(ContentManager.ContentMgr);
在View中使用如下:
<div class="col-md-3">
<hello>Jackie Lee</hello>
<a href="#" author-for="Hello, I'm Jackie Lee.">Welcome to China!</a>
<div author-for="Jackie Lee">Now it is the very good tag.</div>
<p author-for="Well done.">Nice to meet you.</p>
<span author-for="Nice, this is what does for you only.">*</span>
</div>
运行效果:
产生的HTML内容: