解讀ASP.NET 5 & MVC6系列教程(13):TagHelper_自學過程

來源:互聯網
上載者:User

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

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

引入新功能TagHelper以後,我們只需要這樣定義就可以了,代碼如下:

@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以及相關的格式。詳細實現,請參考如下章節中的表格內容。

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

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

屬性 描述
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元素。

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的使用樣本如下,比如我們定義如下代碼:

<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指令碼標籤。其主要原理是如下:

在meta元素上應用定義的carousel-caption樣式。通過JS代碼檢測該meta元素的display屬性是否等於none。如果不等於none,重新載入本地的備用css檔案。

注意,這裡的js指令碼是利用document.getElementsByTagName("SCRIPT"),擷取最後一個SCRIPT標籤的上一個兄弟元素的形式,來擷取meta元素的。

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" >© @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元素。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.