Create TextArea in ASP.NET MVC

The HtmlHelper class includes two extension methods to render multi-line <textarea> HTML control in a razor view: TextArea() and TextAreaFor<TModel, TProperty>(). By default, it creates a textarea with rows=2 and cols=20.

We will use the following Student model class throughout this article.

Example: Student Model
public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public string Description { get; set; }
}

Html.TextAreaFor()

The TextAreaFor<TModel, TProperty>() is the generic extension method that creates <textarea></textarea> control.

It is recommended to use the generic TextAreaFor<TModel, TProperty>() method, which is less error prons and performs fast.

TextAreaFor() Signature
public static MvcHtmlString TextAreaFor<TModel,TProperty> (this HtmlHelper<TModel>> htmlHelper, Expression<Func<TModel,TProperty>> expression, object htmlAttributes);

Visit docs.microsoft.com to know all the overloads of TextAreaFor().

The following example creates and binds the Description property to a textarea control in the MVC view.

Example: TextAreaFor() in Razor View
@model Student

@Html.TextAreaFor(m => m.Description)  
Html Result:
<textarea cols="20" id="Description" name="Description" rows="2"></textarea>

The following example renders a textarea with the class attribute.

Example: TextAreaFor() in Razor View
@model Student

@Html.TextAreaFor(m => m.Description, new { @class = "form-control" })  

In the above example, the first parameter m => m.Description is a lambda expression that specifies the model property to bind with the textarea element. The second parameter specifies the class attribute.

Html Result:
<textarea class="form-control" cols="20" id="Description" name="Description" rows="2"></textarea>

Html.TextArea()

The Html.TextArea() method creates a <textarea> HTML control with specified name, value and html attributes.

The TextArea() method is a loosely typed method because the name parameter is a string. The name parameter can be a property name of the model class.

Example: Html.TextArea() in Razor View
@model Student

@Html.TextArea("Description", "This is dummy description.", new { @class = "form-control" })  
Html Result:
<textarea class="form-control" id="Description" name="Description" rows="2"cols="20">This is dummy description.</textarea>