ASP.NET Core MVC TextArea Tag Helper

In this post from the ASP.NET Core MVC Tag Helper series I will be covering the textarea tag helper.

The textarea tag helper is very similar to the input tag helper but specifically targets the textarea element instead of the input element. The textarea tag helper is used by adding the asp-for tag helper attribute to a text area element.

Consider the following model class:

public class SimpleViewModel
{
    [Required]
    [MaxLength(5000)]
    public string Description { get; set; }
}

We can bind a textarea to the Description property as follows:

<textarea asp-for="Description"></textarea>

…which would generate the following HTML:

<textarea name="Description" id="Description" 
          data-val-required="The Description field is required." 
          data-val-maxlength-max="5000" 
          data-val-maxlength="The field Description must be a string or array type with a maximum length of '5000'." 
          data-val="true"></textarea>

The text area tag helper was able to generate name and id properties based on the name of the property specified in asp-for. It also generated _data-val _attributes to enable client side validation based on the Required and MaxLength attributes that were applied to the model property.

Note: This tag helper is an alternative to the Html.TextAreaFor HTML helper method.

As with the other tag helpers, any HTML attributes that you add to the textarea element will be merged with the generated attributes. For example, adding the rows and cols attributes as follows:

<textarea asp-for="Description" rows="5" cols="40"></textarea>

…would generate the following HTML:

<textarea name="Description" id="Description" 
     rows="5" cols="40" 
     data-val-required="The Description field is required." 
     data-val-maxlength-max="5000" 
     data-val-maxlength="The field Description must be a string or array type with a maximum length of '5000'." 
     data-val="true"></textarea>

That covers everything you need to know about the textarea tag helper. In the next post in the series I will cover the Select tag helper.