開発者ガイド.ネットコアタグヘルパー


ASP .NETコアは、私たちが変更し、サーバー側のCの経典を使用して既存のHTMLマークアップを強化することができます新しい機能“タグヘルパー”を導入しました.私たちは通常、私たちのかみそりのビューとかみそりエンジンでタグヘルパーを追加し、それらを生成し、サーバーから返されるHTMLをレンダリング処理します.これにより、HTMLではC≧のすべてのパワーとクールな機能を使用することができます.タグヘルパーも読みやすく、デザイナーや開発ツールで理解しています.ASP .ネットコアは多くのビルトインタグヘルパー、キャッシュ、アンカー、フォーム、ラベルなどのビルトインされており、我々はまた、ビルトインのタグヘルパーを使用すると同様の方法で独自のカスタムタグヘルパーを作成し、それらを使用することができます.このチュートリアルでは、タグヘルパー対HTMLヘルパー対ビューコンポーネント間の違いを説明します.また、ASPの使い方を説明します.あなたのプロジェクトのネットコアビルトインタグヘルパー.

かみそりビューにおけるタグヘルパーの使用


新しいASPを作成するとき.NETコアMVC Webアプリケーションでは、プロジェクトビュー/Count ViewWiportsで次の行が自動的に追加されます.cshtmlファイル.
@addTagHelper \*, Microsoft.AspNetCore.Mvc.TagHelpers
この行は、@ addtaghelperディレクティブを使用して、すべてのビューで特定のタグまたはすべてのタグヘルパーを登録できます.ここでは、ホームコントローラの既定のインデックスビューに環境タグヘルパーを使用する例を示します.

我々の現在のプロジェクト環境が「開発」としてセットされるので、最初のタグヘルパーだけが以下の通り出力をレンダリングします

@ addTagelperディレクティブには2つのパラメータがあります.最初のパラメータは、タグに含まれるアセンブリの完全修飾名を指定します.上記の行はワイルドカード("*")を使って全てのタグヘルパーを登録しますが、特定のタグヘルパーを登録することもできます.アスピネット.MVCタグヘルパー.Anchortaghelper :
@addTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
上記の行でプロジェクトを構築するとすぐに、Visual Studioが上記の環境タグを認識しておらず、環境要素にTeal Colorを与えないことに注意します.これは、明示的にアンカータグヘルパーのみを我々のビュー/ChangViewMportsに登録するためです.cshtmlファイル.

また、現在のフォルダで利用可能なすべてのビューから特定のタグヘルパーを削除するために使用できる@ removetaghelperディレクティブを使用できます.たとえば、あなたがView/Count ViewMportsを持っているならば.CSHTMLとビュー/アカウント/Core ViewWiports .CSHTMLファイルとすべてのTaghelpersを表示しています.CSHTMLファイルを使用すると、ビュー/アカウント/ChangViewMports内の次の@ removetaghelperディレクティブを使用して、アカウントフォルダ内のすべてのビューからそれらのタグの一部を削除できます.cshtmlファイル.
@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

内蔵のASP .ネットコアタグヘルパー


ASP .NETコアは、マイクロソフトで利用可能な多くのビルトインタグヘルパーで出荷されます.アスピネット.MVCTaghelpers図書館組み込みのタグヘルパーには、妥当性検査に関連するものがあります.の組み込みのタグヘルパーのいくつかを確認してみましょう.

ラベルタグヘルパー


ラベルタグヘルパーはHTMLの代替です.HTMLタグヘルパーを生成する element in HTML. It can also generate the descriptive label value automatically using the Display attribute attached to the property attached to the label. Here is an example of using Label Tag Helper.

Let’s say you have a following class with a property FullName

public class SimpleViewModel
{
   [Required]
   [Display(Name = "Full Name")]
   public string FullName { get; set; }
}

You can use the Label Tag Helper with the above property as follows:

<form asp-controller="Account" asp-action="Register" method="post">
        <label asp-for="FullName"></label>
       <input asp-for="FullName" /> <br />
</form>

The following HTML is generated for the element:

<label for="FullName">Full Name</label>

You can see that we are writing a lot less markup and code is also very easy to read. The FullName property is strongly typed in asp-for attribute of the Label Tag Helper.

Another advantage of using Tag Helpers is that they made developers more productive. Let’s say you are using the above “FullName” property in many forms of your application and one day you decided to change the forms label from “Full Name” to “Your Full Name”, you just have to change the Display attribute [Display(Name = "Your Full Name")] and Label Tag Helper will automatically update in all the forms of your application.

入力タグヘルパー


入力タグヘルパーが HTML element to a model expression in your razor view.
<input asp-for="<Expression Name>">

Let’s say you have a model class with following properties

[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

You can bind these properties with the HTML element as follows:

<form asp-controller="Account" asp-action="Register" method="post">
   Email:  
   <input asp-for="Email" /> 
   <br />
   Password: 
   <input asp-for="Password" />
   <br />
   <button type="submit">Register</button>
</form>

The code above generates the following HTML:

<form method="post" action="/Account/Register"> 
   Email: 
   <input type="email" 
      data-val="true" 
      data-val-email="The Email Address field is not a valid e-mail address." 
      data-val-required="The Email Address field is required." 
      id="Email" name="Email" value="" /> 
   <br /> 
   Password: 
   <input type="password" 
      data-val="true" 
      data-val-required="The Password field is required." 
      id="Password" name="Password" /> 
   <br /> 
   <button type="submit">Register</button> 
   <input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

You can see from the above generated HTML that Input Tag Helper is a powerful tag helper because it is generating a lot of HTML markup which we were normally used to write manually in our Razor Views in the past. Input Tag Helper has the following features:

  • It generates id and name attributes matching with the asp-for expression name e.g. Email
  • It automatically set the correct HTML type attribute based on the DataType data annotation 属性の例
  • を使用して自動的にHTMLdata annotations モデル特性への応用例えば必須のデータval
  • これは、モデルプロパティの名前が変更された場合、コンパイル時のエラーをRazorビューで取得することを意味する強力なタイピング機能を提供します.
  • 入力タグヘルパーについての詳細情報はhere .

    Textareaタグヘルパー


    TextAreaタグヘルパーは、入力タグヘルパーと非常によく似ており、モデルからID、名前、およびデータ検証属性を生成します.これは、RazorビューでHTML要素を生成し、入力タグヘルパーと同じように強い入力をサポートしています.
    あなたのモデルクラスに次のプロパティがあるとしましょう
    [MinLength(5)]
    [MaxLength(1024)]
    public string Description { get; set; }
    
    TextAreaタグヘルパーで上記のプロパティを使用できます
    <textarea asp-for="Description"></textarea>
    
    上記のタグヘルパーは次のHTML出力を生成します
    <textarea data-val="true"
       data-val-maxlength="The field Description must be a string or array type with a maximum length of ‘1024’."
       data-val-maxlength-max="1024"
       data-val-minlength="The field Description must be a string or array type with a minimum length of ‘5’."
       data-val-minlength-min="5"
       id="Description" name="Description">
    </textarea>
    

    タグの選択


    selectタグヘルパーはHTMLを生成するselect 連想する要素option 要素.HTMLヘルパー機能HTMLの代替です.ドロップダウンリストとHTML.リストボックスその最も一般的な属性はASPです.そして、それはBINDへのモデルプロパティ名とオプション要素を指定するASPアイテムを指定します.
    selectタグヘルパーを使用するには、次の2つのプロパティを使用してモデルを作成できます.
    public class UserInfo
    {
        public string Color { get; set; }
    
        public List<SelectListItem> Colors { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "Red" },
            new SelectListItem { Value = "2", Text = "Green" },
            new SelectListItem { Value = "3", Text = "Blue"  },
        };
    }
    
    MVCコントローラでモデルを初期化し、次のようにモデルをRazorビューに渡すことができます.
    using System;
    
    public IActionResult Index()
    {
        var model = new UserInfo();
        model.Color = "1";
    
        return View(model);
    }
    
    最後に、次のようにselectタグヘルパーを使用できます.
    <select asp-for="Color" asp-items="Model.Colors"></select>
    
    上記の選択タグヘルパーを使用して、次のHTMLマークアップが生成されます
    <select id="Color" name="Color">
       <option selected="selected" value="1">Red</option>
       <option value="2">Green</option>
       <option value="3">Blue</option>
    </select>
    

    フォームタグヘルパー


    フォームタグヘルパーは、かみそりのビューでHTMLフォームを生成するのに便利です.
    <form asp-controller="Account" asp-action="Register" method="post">
        <!-- Input and Submit elements -->
    </form>
    
    フォームタグヘルパーは、次のHTMLを生成します.
    <form method="post" action="/Demo/Register">
        <!-- Input and Submit elements -->
        <input name="\_\_RequestVerificationToken" type="hidden" value="<removed for brevity>">
    </form>
    
    フォームタグヘルパーには以下の機能があります.
  • HTMLを生成するform > 要素と自動的にMVCコントローラアクションまたは名前付きルートとのアクション属性のマッチングを設定します.
  • これはRequest Verification Token 防ぐ要素cross-site request forgery アタック.
  • フォームタグヘルパーの詳細についてはhere .

    アンカータグヘルパー


    標準HTML <a > 要素は非常にシンプルなタグで、クライアント側のHTMLでのみ動作します.アンカータグヘルパーは標準<a > タグと多くの新しい属性を提供します.ASPコントローラ属性はMVCコントローラを要素に割り当てます、そして、それは特定のMVCコントローラを指すURLを生成するのに役に立ちます.ASP Action Attributeは特定のMVCアクションをa > 要素を指定し、a > HREF属性.ここではアンカーのタグヘルパーのいくつかの例です.
    アンカータグヘルパー
    生成HTML出力<a asp-controller="Product" asp-action="Index">Products List</a> <a href=”/Product”>Products List</a> <a asp-controller="Product" asp-action="Tags">Products Tags</a> <a href=”/Product/Tags”>Products List</a>アンカータグヘルパーは、これらの属性について多くの他の属性と完全な詳細がありますhere .

    イメージタグヘルパー


    イメージタグヘルパーは、ビルトインのHTML 要素とキャッシュバスティンと呼ばれる追加機能を提供します.キャッシュバスティンは、我々がイメージファイルURLでユニークなバージョンを追加することによってブラウザーキャッシュ問題を解決するのに用いられるテクニックです.たびに、このユニークなバージョンが変更され、ブラウザは、ローカルのキャッシュされたバージョンのイメージを無視し、サーバーから画像の更新/新しいバージョンを取得しようとします.イメージタグヘルパーには、ASP Appendバージョンと呼ばれるプロパティがありますcache-busting 機能.
    <img src="~/images/logo.jpg" asp-append-version="true">
    
    上記のイメージタグヘルパーは、次のHTMLマークアップを生成します.独自のハッシュ文字列を追加します.
    <img src="/images/logo.jpg?v=Kl_dqr9NVtnMdsM2MUg4qthUnWZm5T1fCEimBPWDNgM">
    

    概要


    このチュートリアルでは、いくつかのビルトインのタグヘルパーをカバーしようとしました.ASP .ネットコアは、より生産的にすることができますより便利なタグヘルパーと出荷されます.あなたが内蔵のタグヘルパーの完全なリストを探索する場合は、マイクロソフトを訪問することができますofficial docs はい.