Nguon: Microsoft Learn · .NET 8.0

Textarea Tag Helper trong ASP.NET Core

Nguồn: Tag Helpers in forms - The Textarea Tag Helper

Textarea Tag Helper

Textarea Tag Helper (Tag Helper Textarea) tương tự như Input Tag Helper (Tag Helper Input).

Ví dụ:

csharp
using System.ComponentModel.DataAnnotations;

namespace FormsTagHelper.ViewModels
{
    public class DescriptionViewModel
    {
        [MinLength(5)]
        [MaxLength(1024)]
        public string Description { get; set; }
    }
}
cshtml
@model DescriptionViewModel

<form asp-controller="Demo" asp-action="RegisterTextArea" method="post">
    <textarea asp-for="Description"></textarea>
    <button type="submit">Test</button>
</form>

HTML được tạo ra:

html
<form method="post" action="/Demo/RegisterTextArea">
  <textarea data-val="true"
   data-val-maxlength="The field Description must be a string or array type with a maximum length of &#x27;1024&#x27;."
   data-val-maxlength-max="1024"
   data-val-minlength="The field Description must be a string or array type with a minimum length of &#x27;5&#x27;."
   data-val-minlength-min="5"
   id="Description" name="Description">
  </textarea>
  <button type="submit">Test</button>
  <input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>">
</form>

Textarea Tag Helper tự động thêm các thuộc tính data-val-* dựa trên data annotation (chú thích dữ liệu) như [MinLength][MaxLength] được áp dụng cho property của model. Điều này cung cấp tính năng xác thực phía client bằng HTML5 và jQuery.