役割
• for 属性を自動生成してくれる
• モデルの Display 名や DataAnnotations を反映する
• バリデーションメッセージと連動する
for 属性とは
要素がどのフォームコントロール(inputやbuttonなど)と関連付けられているかを明示するために使われる属性です。
具体例
Models/Customer.cs
[Required(ErrorMessage = "氏名(漢字)は必須です。")]
[MaxLength(100)]
public string FullName { get; set; } = string.Empty;
モデルで、エラーメッセージ、MaxLengthを定義。
Views/LifeInsuranceMvc/AddCustomer.cshtml
<div>
<label asp-for="FullName">氏名</label>
<input asp-for="FullName" class="form-control" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
asp-for="FullName"によって、モデルのエラーメッセージ、MaxLengthの設定が連動されます。