TagHelper(標籤助手)是ASP.NET Core很是好的一種新特性。能夠擴展視圖,讓其看起來像一個原生HTML標籤。html
應該使用TagHelper替換HtmlHelper,因其更簡潔更易用,且支持依賴注入。能夠經過其構造函數中注入所須要的服務。ide
下面使用一個簡單的標籤示例擴展:函數
1 [HtmlTargetElement("hello")] 2 public class HelloTagHelper : TagHelper 3 { 4 public override void Process(TagHelperContext context, TagHelperOutput output) 5 { 6 output.TagName = "p"; 7 output.Attributes.Add("id", context.UniqueId); 8 output.Attributes.Add("style", "color:red;font-weight:bold;"); 9 output.PreContent.SetContent("Hello "); 10 output.PostContent.SetContent($", time is now: {DateTime.Now.ToString("HH:mm:")}"); 11 } 12 }
在此定義了一個「hello」標籤,能夠像其餘標識同樣使用。ui
不過前提得先將該標籤所在的命名空間引用到到cshtml文件中(此處使用"_ViewImports.cshtml"進行設置)this
1 @addTagHelper "*, TagAbout"
在View中使用,如在Index.cshtml中使用,以下:spa
<div class="col-md-3"> <hello>Jackie Lee</hello> </div>
運行效果:3d
產生的HTML以下:code
定義a、p、ul、li、button、span、div標籤的屬性擴展TagHelper類以下,爲其內容最後添加一段經過依賴注入進來的類調用返回的內容。htm
併爲其添加title屬性,以提示「author-for"所設置的內容:對象
1 [HtmlTargetElement("a", Attributes = ForAttributeName)] 2 [HtmlTargetElement("p", Attributes = ForAttributeName)] 3 [HtmlTargetElement("ul", Attributes = ForAttributeName)] 4 [HtmlTargetElement("li", Attributes = ForAttributeName)] 5 [HtmlTargetElement("button", Attributes = ForAttributeName)] 6 [HtmlTargetElement("span", Attributes = ForAttributeName)] 7 [HtmlTargetElement("div", Attributes = ForAttributeName)] 8 public class AuthorTagHelper : TagHelper 9 { 10 private const string ForAttributeName = "author-for"; 11 private const string TextAttributeName = "content"; 12 13 [HtmlAttributeName(ForAttributeName)] 14 public string AuthorFor { get; set; } 15 16 private ContentManager _contentManager; 17 18 public AuthorTagHelper(ContentManager contentManager) 19 { 20 _contentManager = contentManager; 21 } 22 23 public override void Process(TagHelperContext context, TagHelperOutput output) 24 { 25 output.Attributes.Add("title", AuthorFor); 26 output.PostContent.AppendHtml($"<span style='font-weight:bold;color:orange;'>[{_contentManager.GetContent()}]</span>"); 27 // 可用於驗證 28 if (false) 29 { 30 var builder = output.Content; 31 output.SuppressOutput(); // nothing to output 32 builder.AppendHtml(string.Empty); 33 } 34 } 35 }
依賴注入的類:
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內容: