標籤:http imp time welcome nbsp sso 視圖 als append
TagHelper(標籤助手)是ASP.NET Core非常好的一種新特性。可以擴充視圖,讓其看起來像一個原生HTML標籤。
應該使用TagHelper替換HtmlHelper,因其更簡潔更易用,且支援依賴注入。可以通過其建構函式中注入所需要的服務。
一、擴充的標籤:
下面使用一個簡單的標籤樣本擴充:
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”標籤,可以像其他標識一樣使用。
不過前提得先將該標籤所在的命名空間引用到到cshtml檔案中(此處使用"_ViewImports.cshtml"進行設定)
1 @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"所設定的內容:
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 output32 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內容:
asp.net core的TagHelper簡單使用