1. 程式人生 > 實用技巧 >asp.net core2 mvc 基礎教程--再講 Tag Helpers

asp.net core2 mvc 基礎教程--再講 Tag Helpers

Tag Helpers

  • Tag Helpers 是伺服器端的 C# 程式碼,它在 Razor 檔案裡,它會參與到建立和渲染 HTML 元素過程中
  • 和 HTML Helpers 類似
  • 跟 HTML 的命名規範一致
  • 內建了很多 Tag Helpers,也可以自定義

JavaScript Tag Helpers

  • asp-src-include
  • asp-src-exclude
  • asp-fallback-src:指定回落檔案
  • asp-fallback-test:回落測試
<script asp-src-include="~/app/**/*.js"
        asp-src-exclude="~/app/services/**/*.js">
</script>

測試預設 js 裡面有沒有 window.jQuery 物件,如果沒有就使用回落源。

<script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js"
        asp-fallback-src="-/lib/bootstrap/js/bootstrap.min.js
" asp-fallback-test="window.jQuery"> </script>

CSS Tag Helpers

回落測試:CDN 的 CSS 中是否有 hidden class,hidden class 中是否有 visibility property,且其值為 hidden。

<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.8.e/css/bootstrap.min.css"
      asp-fallback-href="/lib/bootstrap/css/bootstrap.min.css
" asp-fallback-test-class="hidden" asp-fallback-test-property="visibility" asp-fallback-test-value="hidden"/>

其它 Tag Helpers

  • asp-append-version
  • <img src="~/images/asplogo.png" asp-append-version="true" />
  • <img src="/images/asplogo.png?v=KI_dqr9NVtnMdsM2MUg4qthUnWzm5T1fCEimBPWDNgM" />

asp-append-version 生成了圖片檔案的 Hash 值,並附到圖片連結後面。

環境的 Tag Helpers

<environment names="Staging,Production">
  <strong>HostingEnvironment.EnvironmentName is Staging or Production</strong>
</environment>
<environment include="Staging,Production">
    <strong>HostingEnvironment.EnvironmentName is Staging or Production</strong>
</environment>
<environment exclude="Development">
    <strong>HostingEnvironment.EnvironmentName is not Development</strong>
</environment>

自定義 Tag Helpers

  1. 繼承 TagHelper 父類
  2. 實現(override)Process 方法
  1. 或實現非同步的 ProcessAsync 方法

記得需在 _ViewImport 中注入 @addTagHelper *, Heavy.Web

同步實現

public class EmailTagHelper : TagHelper
{
    public string MailTo { get; set; }
    public override void Process(
        TagHelperContext context,
        TagHelperOutput output)
    {
        // Replaces <email> with <a> tag
        output.TagName = "a";
        output.Attributes.SetAttribute("href", $"mailto:{MailTo}");
        output.Content.SetContent(MailTo);
    }
}

使用和效果:

<email mail-to="[email protected]"></email>
<a href="mailto:[email protected]">[email protected]</a>

非同步實現

public override async Task ProcessAsync(
    TagHelperContext context,
    TagHelperOutput output)
{
    output.TagName = "a";
    var content = await output.GetChildContentAsync();
    var target = content.GetContent();
    output.Attributes.SetAttribute("href", $"mailto:{target}");
    output.Content.SetContent(target);
}

使用和效果:

<email>[email protected]</email>
<a href="mailto:[email protected]">[email protected]</a>

作為元素級 & 作為屬性

兩種用法:

<bold color="green">這個是粗體字嗎?</bold>
<p bold color="red">應該是粗體字。</p>

BoldTagHelper:

[HtmlTargetElement("bold")]
[HtmlTargetElement(Attributes = "bold")]
public class BoldTagHelper : TagHelper
{
    [HtmlAttributeName("color")]
    public string MyColor { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.Attributes.RemoveAll("bold");
        output.PreContent.SetHtmlContent("<strong>");
        output.PostContent.SetHtmlContent("</strong>");
        output.Attributes.SetAttribute("style", $"color:{MyColor};");
    }
}

複雜的 Tag Helper 屬性

Model 類 MyStyle :

namespace Heavy.Web.TagHelpers.Models
{
    public class MyStyle
    {
        public string Color { get; set; }
        public int FontSize { get; set; }
        public string FontFamily { get; set; }
    }
}

使用了 MyStyle 屬性的 BlodTagHelper:

[HtmlTargetElement("bold")]
[HtmlTargetElement(Attributes = "bold")]
public class BoldTagHelper : TagHelper
{
    [HtmlAttributeName("my-style")]
    public MyStyle MyStyle { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.Attributes.RemoveAll("bold");
        output.PreContent.SetHtmlContent("<strong>");
        output.PostContent.SetHtmlContent("</strong>");
        output.Attributes
            .SetAttribute("style", $"color: {MyStyle.Color}; font-size: {MyStyle.FontSize}; font-family: {MyStyle.FontFamily};");
    }
}

使用:

<p bold my-style="@(new MyStyle
                    {
                        Color = "red",
                        FontSize = 30,
                        FontFamily = "SimHei"
                    })">應該是粗體字。</p>

效果:

<p style="color: red; font-size: 30; font-family: SimHei;"><strong>應該是粗體字。</strong></p>

注:更多關於自定義 Tag Helpers 的知識請參考 Docs