解讀ASP.NET 5 & MVC6系列(13):TagHelper

在新版的MVC6中,微軟提供了強大的TagHelper功能,以便讓咱們擺脫以下的臃腫代碼:css

@Html.LabelFor(model => model.FullName)
@Html.EditFor(model => model.FullName)
@Html.ValidationMessageFor(model => model.FullName)

引入新功能TagHelper之後,咱們只須要這樣定義就能夠了,代碼以下:html

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"  /* 這裏須要首先引用TagHelper所在的命名空間 */

<label asp-for="FullName" class="control-label col-md-2"></label>
<div class="col-md-10">
    <input asp-for="FullName" class="form-control" />
    <span asp-validation-for="FullName"></span>
</div>

這種方式,拋去了服務器端代碼,利用自定義html屬性顯得更加有語義,前端人員開起來也很舒服,極大地提升了前端開發人員的效率。前端

在默認的TagHelper實現裏,不一樣的元素支持不一樣的自定義屬性,以實現不一樣的用途,例如大部分元素都支持asp-for,而a元素則支持asp-controllerasp-action等,input元素最強大的,支持各類類型的type以及相關的格式。詳細實現,請參考以下章節中的表格內容。jquery

A元素

屬性 描述
asp-controller Controller的名稱
asp-action Action的名稱
asp-host 網站的Host
asp-fragment URL的fragment名稱
asp-protocol 網站協議(http或https)
asp-route Route名稱
asp-route-
href 默認屬性,若是href有值,則其它屬性都不能設置任何值。

Form元素

屬性 描述
asp-controller Controller的名稱
asp-action Action的名稱
asp-anti-forgery
asp-route-
action 默認屬性,若是action有值,則其它屬性都不能設置任何值。

Input元素

屬性 描述
asp-for 模型字段的名稱
asp-format 設置Type格式,具體以下:
格式 標準類型
HiddenInput hidden
Password password
Text text
PhoneNumber tel
Url url
EmailAddress email
Date date
DateTime datetime
DateTime-local datetime-local
Time time
Byte/SByte/Int16/UInt16/Int32/UInt32/Int64/UInt64/Single/Double number
Boolean checkbox
Decimal text
String text
IFormFile file
IEnumerable`IFormFile file

其中關於時間的具體格式以下:web

屬性 描述
date {0:yyyy-MM-dd}
datetime {0:yyyy-MM-ddTHH:mm:ss.fffK}
datetime-local {0:yyyy-MM-ddTHH:mm:ss.fff}
time {0:HH:mm:ss.fff}

Label元素

屬性 描述
asp-for 模型字段的名稱

textarea元素

屬性 描述
asp-for 模型字段的名稱

span元素

屬性 描述
asp-validation-for 模型字段的名稱

div元素

屬性 描述
asp-validation-aummary ValidationSummary枚舉值:
ValidationSummary.All
ValidationSummary.ModelOnly
ValidationSummary.None。

驗證描述類型,只有選擇了ValidationSummary.All和ValidationSummary.ModelOnly才能渲染該div元素。ajax

select元素

屬性 描述
asp-for 模型字段名稱
asp-items 模型字段名稱

link元素

屬性 描述
asp-href-include
asp-href-exclude
asp-fallback-href 默認href加載失敗時的備用地址
asp-fallback-href-include
asp-fallback-href-exclude
asp-fallback-test-class 判斷加載失敗時用到的class樣式
asp-fallback-test-property 判斷加載失敗時用到的class樣式中的屬性
asp-fallback-test-value 判斷加載失敗時用到的class樣式中的屬性對應的值
asp-file-version
href 默認加載的css文件地址。

link的使用示例以下,好比咱們定義以下代碼:bootstrap

<link rel="stylesheet" 
href="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/bootstrap-touch-carousel.css"
asp-fallback-href="~/lib/bootstrap-touch-carousel/css/bootstrap-touch-carousel.css"
asp-fallback-test-class="carousel-caption" 
asp-fallback-test-property="display" 
asp-fallback-test-value="none" />

則該段代碼表示,默認先加載aspnetcdn.com上的css文件,若是加載失敗了,再加載本地網站裏的css文件,加載失敗的判斷條件是:檢測carousel-caption樣式十分應用上了,即該應用了該樣式的元素的display屬性是否等於none。運行網站後,這段代碼的生成html以下:服務器

<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/bootstrap-touch-carousel.css" />
<meta name="x-stylesheet-fallback-test" class="carousel-caption" />
<script>
    !function (a, b, c) {
        var d, e = document,
            f = e.getElementsByTagName("SCRIPT"),
            g = f[f.length - 1].previousElementSibling,
            h = e.defaultView && e.defaultView.getComputedStyle ? e.defaultView.getComputedStyle(g) : g.currentStyle;

        if (h && h[a] !== b) {
            for (d = 0; d < c.length; d++) {
                e.write('<link rel="stylesheet" href="' + c[d] + '"/>')
            }
        }
    }("display", "none", ["\/lib\/bootstrap-touch-carousel\/css\/bootstrap-touch-carousel.css"]);
</script>

從中,咱們看到,生成的HTML代碼在link元素以後多了兩個元素,一個是帶有class="carousel-caption"屬性的meta元素,一個是script腳本標籤。其主要原理是以下:cookie

  1. 在meta元素上應用定義的carousel-caption樣式。
  2. 經過JS代碼檢測該meta元素的display屬性是否等於none
  3. 若是不等於none,從新加載本地的備用css文件。

注意,這裏的js腳本是利用document.getElementsByTagName("SCRIPT"),獲取最後一個SCRIPT標籤的上一個兄弟元素的形式,來獲取meta元素的。async

script元素

屬性 描述
asp-src-include
asp-src-exclude
asp-fallback-src 備用js文件地址
asp-fallback-src-include
asp-fallback-src-exclude
asp-fallback-test 判斷默認js文件是否加載成功用到的對象
asp-file-version
src 默認的js文件地址。

script標籤元素的fallback功能,和link元素記載css文件類型,只不過這裏判斷的不是class樣式,而是檢測某個對象是否存在,來判斷默認的js文件是否加載成功,示例以下:

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

生成後的HTML代碼,相對比較簡單,示例以下:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js">
</script>
<script>(window.jQuery||document.write("<script src=\"\/lib\/jquery\/jquery.min.js\"><\/script>"));</script>

多生成了一個script標籤元素,而後判斷jQuery對象是否存在,若是不存在則表示加載失敗,那就再加載本地的備用js文件。

Cache

屬性 描述
vary-by
vary-by-header
vary-by-query
vary-by-route
vary-by-cookie
vary-by-user
expires-on
expires-after
expires-sliding
priority
enabled .

利用EnvironmentTagHelper來控制不一樣運行環境的輸出結果

在不少狀況下,咱們想再開發環境使用一套配置信息,在生產環境又是另一套,這時候就須要使用條件判斷語句了,不過在新版的MVC中,使用EnvironmentTagHelper提供的Environment元素標籤就能夠了,示例以下:

<environment names="Development">
    <script src="~/lib/jquery/jquery.js"></script>
    <script src="~/lib/bootstrap/js/bootstrap.js"></script>
    <script src="~/lib/hammer.js/hammer.js"></script>
    <script src="~/lib/bootstrap-touch-carousel/js/bootstrap-touch-carousel.js"></script>
</environment>
<environment names="Staging,Production">
    <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js"
            asp-fallback-src="~/lib/jquery/jquery.min.js"
            asp-fallback-test="window.jQuery">
    </script>
    <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>
    <script src="//ajax.aspnetcdn.com/ajax/hammer.js/2.0.4/hammer.min.js"
            asp-fallback-src="~/lib/hammer.js/hammer.js"
            asp-fallback-test="window.Hammer">
    </script>
    <script src="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/js/bootstrap-touch-carousel.js"
            asp-fallback-src="~/lib/bootstrap-touch-carousel/js/bootstrap-touch-carousel.js"
            asp-fallback-test="window.Zepto">
    </script>
</environment>

在上述代碼中,咱們定於,若是是Development環境就使用本地的js文件,不然(Staging或Production環境)就先加載cdn的文件(只不過還留有備用方案)。

該names裏的值判斷依據是,查找IHostingEnvironmentEnvironmentName屬性,並與其進行比較,而後再進行相應的處理。

自定義TagHelper

MVC全部TagHelper的實現,都繼承了Microsoft.AspNet.Razor.Runtime.TagHelpers.ITagHelper接口,因此咱們只要實現該接口就能夠實現自定義的TagHelper,該接口的定義以下:

public interface ITagHelper
{
    int Order { get; }
    Task ProcessAsync(TagHelperContext context, TagHelperOutput output);
}

不過,咱們通常自定義的時候,只須要繼承該接口的默認實現TagHelper類,並重載其虛方法Process方法便可,以下是幾個示例,咱們來詳細研究一下。

1. 在a元素上直接支持controller和action屬性

public class ATagHelper : TagHelper
{
    [Activate]
    public IUrlHelper UrlHelper { get; set; }

    public string Controller { get; set; }

    public string Action { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (Controller != null && Action != null)
        {
            var methodParameters = output.Attributes.ToDictionary(attribute => attribute.Key,
                                                                    attribute => (object)attribute.Value);

            // 刪除全部的attributes,由於路由裏已經能夠自動生成了
            output.Attributes.Clear();

            output.Attributes["href"] = UrlHelper.Action(Action, Controller, methodParameters);

            output.PreContent.SetContent("My ");
        }
    }
}

2. 自動識別Text文本中的連接,並提取出來

[TargetElement("p")]
public class AutoLinkerTagHelper : TagHelper
{
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var childContent = await context.GetChildContentAsync();

        // Find Urls in the content and replace them with their anchor tag equivalent.
        output.Content.SetContent(Regex.Replace(
            childContent.GetContent(),
            @"\b(?:https?://|www\.)(\S+)\b",
            "<strong><a target=\"_blank\" href=\"http://$0\">$0</a></strong>"));
    }
}

3. 條件判斷

定義一個condiction,符合條件才顯示該元素,示例以下(只有Model.Approved爲true時才顯示該元素):

<p condition="Model.Approved" >&copy; @Model.CopyrightYear - My ASP.NET Application</p>

實現代碼以下:

[TargetElement("div")]
[TargetElement("style")]
[TargetElement("p")]
public class ConditionTagHelper : TagHelper
{
    public bool? Condition { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // 若是設置了condition,而且該值爲false,則不渲染該元素
        if (Condition.HasValue && !Condition.Value)
        {
            output.SuppressOutput();
        }
    }
}

4. 自定義元素的TagHelper

若是咱們要爲自定義元素定義TagHelper,則咱們要符合約定規範,示例代碼以下:

public class WebsiteInformationTagHelper : TagHelper
{
    public WebsiteContext Info { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "section";
        output.PostContent.SetContent(string.Format(
            "<p><strong>Version:</strong> {0}</p>" + Environment.NewLine +
            "<p><strong>Copyright Year:</strong> {1}</p>" + Environment.NewLine +
            "<p><strong>Approved:</strong> {2}</p>" + Environment.NewLine +
            "<p><strong>Number of tags to show:</strong> {3}</p>" + Environment.NewLine,
            Info.Version.ToString(),
            Info.CopyrightYear.ToString(),
            Info.Approved.ToString(),
            Info.TagsToShow.ToString()));
        output.SelfClosing = false;
    }
}

則使用的時候,咱們須要使用website-information標籤,並將info屬性賦值一個強類型的值,示例以下:

<website-information info="new WebsiteContext {
                                Version = new Version(1, 1),
                                CopyrightYear = 1990,
                                Approved = true,
                                TagsToShow = 30 }"/>

其渲染結果,則是渲染成一個包含4個p元素的section元素。

同步與推薦

本文已同步至目錄索引:解讀ASP.NET 5 & MVC6系列

相關文章
相關標籤/搜索