欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年06月24日 12:02:22   作者:湯姆大叔  
這篇文章主要介紹了新版MVC6中強(qiáng)大的TagHelper功能,需要的朋友可以參考下

在新版的MVC6中,微軟提供了強(qiáng)大的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>

這種方式,拋去了服務(wù)器端代碼,利用自定義html屬性顯得更加有語(yǔ)義,前端人員開(kāi)起來(lái)也很舒服,極大地提高了前端開(kāi)發(fā)人員的效率。

在默認(rèn)的TagHelper實(shí)現(xiàn)里,不同的元素支持不同的自定義屬性,以實(shí)現(xiàn)不同的用途,例如大部分元素都支持asp-for,而a元素則支持asp-controllerasp-action等,input元素最強(qiáng)大的,支持各種類型的type以及相關(guān)的格式。詳細(xì)實(shí)現(xiàn),請(qǐng)參考如下章節(jié)中的表格內(nèi)容。

A元素

屬性 描述
asp-controller Controller的名稱
asp-action Action的名稱
asp-host 網(wǎng)站的Host
asp-fragment URL的fragment名稱
asp-protocol 網(wǎng)站協(xié)議(http或https)
asp-route Route名稱
asp-route-
href 默認(rèn)屬性,如果href有值,則其它屬性都不能設(shè)置任何值。

Form元素

屬性 描述
asp-controller Controller的名稱
asp-action Action的名稱
asp-anti-forgery
asp-route-
action 默認(rèn)屬性,如果action有值,則其它屬性都不能設(shè)置任何值。

Input元素

屬性 描述
asp-for 模型字段的名稱
asp-format 設(shè)置Type格式,具體如下:
格式 標(biāo)準(zhǔn)類型
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

其中關(guān)于時(shí)間的具體格式如下:

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

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

select元素

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

link元素

屬性 描述
asp-href-include
asp-href-exclude
asp-fallback-href 默認(rèn)href加載失敗時(shí)的備用地址
asp-fallback-href-include
asp-fallback-href-exclude
asp-fallback-test-class 判斷加載失敗時(shí)用到的class樣式
asp-fallback-test-property 判斷加載失敗時(shí)用到的class樣式中的屬性
asp-fallback-test-value 判斷加載失敗時(shí)用到的class樣式中的屬性對(duì)應(yīng)的值
asp-file-version
href 默認(rèn)加載的css文件地址。

link的使用示例如下,比如我們定義如下代碼:

<link rel="stylesheet" 

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" />

則該段代碼表示,默認(rèn)先加載aspnetcdn.com上的css文件,如果加載失敗了,再加載本地網(wǎng)站里的css文件,加載失敗的判斷條件是:檢測(cè)carousel-caption樣式十分應(yīng)用上了,即該應(yīng)用了該樣式的元素的display屬性是否等于none。運(yùn)行網(wǎng)站后,這段代碼的生成html如下:

<link rel="stylesheet"  />
<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元素之后多了兩個(gè)元素,一個(gè)是帶有class="carousel-caption"屬性的meta元素,一個(gè)是script腳本標(biāo)簽。其主要原理是如下:

在meta元素上應(yīng)用定義的carousel-caption樣式。通過(guò)JS代碼檢測(cè)該meta元素的display屬性是否等于none。如果不等于none,重新加載本地的備用css文件。

注意,這里的js腳本是利用document.getElementsByTagName("SCRIPT"),獲取最后一個(gè)SCRIPT標(biāo)簽的上一個(gè)兄弟元素的形式,來(lái)獲取meta元素的。

script元素

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

script標(biāo)簽元素的fallback功能,和link元素記載css文件類型,只不過(guò)這里判斷的不是class樣式,而是檢測(cè)某個(gè)對(duì)象是否存在,來(lái)判斷默認(rèn)的js文件是否加載成功,示例如下:

<script src="http://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代碼,相對(duì)比較簡(jiǎn)單,示例如下:

<script src="http://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>

多生成了一個(gè)script標(biāo)簽元素,然后判斷jQuery對(duì)象是否存在,如果不存在則表示加載失敗,那就再加載本地的備用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來(lái)控制不同運(yùn)行環(huán)境的輸出結(jié)果

在很多情況下,我們想再開(kāi)發(fā)環(huán)境使用一套配置信息,在生產(chǎn)環(huán)境又是另外一套,這時(shí)候就需要使用條件判斷語(yǔ)句了,不過(guò)在新版的MVC中,使用EnvironmentTagHelper提供的Environment元素標(biāo)簽就可以了,示例如下:

<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="http://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="http://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="http://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="http://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環(huán)境就使用本地的js文件,否則(Staging或Production環(huán)境)就先加載cdn的文件(只不過(guò)還留有備用方案)。

該names里的值判斷依據(jù)是,查找IHostingEnvironmentEnvironmentName屬性,并與其進(jìn)行比較,然后再進(jìn)行相應(yīng)的處理。

自定義TagHelper

MVC所有TagHelper的實(shí)現(xiàn),都繼承了Microsoft.AspNet.Razor.Runtime.TagHelpers.ITagHelper接口,所以我們只要實(shí)現(xiàn)該接口就可以實(shí)現(xiàn)自定義的TagHelper,該接口的定義如下:

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

不過(guò),我們一般自定義的時(shí)候,只需要繼承該接口的默認(rèn)實(shí)現(xiàn)TagHelper類,并重載其虛方法Process方法即可,如下是幾個(gè)示例,我們來(lái)詳細(xì)研究一下。

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,因?yàn)槁酚衫镆呀?jīng)可以自動(dòng)生成了
   output.Attributes.Clear();

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

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

2. 自動(dòng)識(shí)別Text文本中的鏈接,并提取出來(lái)

[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. 條件判斷

定義一個(gè)condiction,符合條件才顯示該元素,示例如下(只有Model.Approved為true時(shí)才顯示該元素):

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

實(shí)現(xiàn)代碼如下:

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

 public override void Process(TagHelperContext context, TagHelperOutput output)
 {
  // 如果設(shè)置了condition,并且該值為false,則不渲染該元素
  if (Condition.HasValue && !Condition.Value)
  {
   output.SuppressOutput();
  }
 }
}

4. 自定義元素的TagHelper

如果我們要為自定義元素定義TagHelper,則我們要符合約定規(guī)范,示例代碼如下:

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;
 }
}

則使用的時(shí)候,我們需要使用website-information標(biāo)簽,并將info屬性賦值一個(gè)強(qiáng)類型的值,示例如下:

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

其渲染結(jié)果,則是渲染成一個(gè)包含4個(gè)p元素的section元素。

相關(guān)文章

最新評(píng)論