TextArea HTML Helper in ASP.NET Core MVC

TextArea HTML Helper in ASP.NET Core MVC

In this article, I will discuss the TextArea HTML Helper Method in ASP.NET Core MVC Application with Examples. Please read our previous article discussing the TextBox HTML Helper in ASP.NET Core MVC Application.

What is TextArea in Web Application?

The TextArea in Web Applications refers to an element that allows users to input multiple lines of text. It is a form control that can capture user input, such as comments, descriptions, or any other information that requires more than a single line of text. Unlike a single-line text input field (often created using an <input type=”text”> tag in HTML), a TextArea provides a larger, flexible area for text entry, making it suitable for inputs that require more extensive content.

The TextArea element is defined in HTML using the <textarea> tag. This tag can include attributes to control its appearance and functionality, such as rows and cols to specify its size, placeholder for placeholder text, maxlength to limit the number of characters a user can enter, and readonly or disabled to control user interaction.

How Do We Create TexArea using HTML Helper in ASP.NET Core MVC Application?

In ASP.NET Core MVC, the TextArea HTML helper is used to generate a multiline text input element (i.e., a <textarea> tag) in Razor views. It allows users to input multiple lines of text. This is particularly useful when dealing with form fields that require larger amounts of text input, such as comments or descriptions. The IHtmlHelper class provides two extension methods to generate the textarea: They are TextArea() and TextAreaFor().

The Html.TextArea method is used when you want to specify the name of the form field manually, while Html.TextAreaFor is used with model properties, providing a strongly typed approach. That means the TextArea() HTML Helper method is loosely typed, whereas the TextAreaFor() HTML Helper method is strongly typed.

TextArea() HTML Helper Method in ASP.NET Core MVC:

The TextArea() HTML Helper method is a loosely typed helper method because the name parameter is a string. As shown in the image below, there are four overloaded versions available for the TextArea() HTML Helper Method in ASP.NET Core MVC.

TextArea() HTML Helper Method in ASP.NET Core MVC

Parameters:
htmlHelper:

The htmlHelper property refers to the instance of the HtmlHelper class, which provides methods for rendering HTML controls in Razor views, such as input fields, buttons, dropdowns, etc. The htmlHelper is implicitly available in Razor views as @Html and is used to invoke HTML helper methods, like TextArea, to generate HTML elements.

For example: @Html.TextArea(“Description”)
Here, Html is an instance of the htmlHelper, and you are calling the TextArea method on it to generate a <textarea> element.

expression:

In the context of the TextArea helper method, the expression refers to the name of the form field or model property to which the generated <textarea> will be bound. It is a string that specifies the name or the “expression” that will map to a key in the form’s posted data.

For example: @Html.TextArea(“Description”)
Here, “Description” is the expression that specifies the name attribute of the generated <textarea> element. It does not have to be bound to a model but can simply represent the name used to access the value when the form is submitted.

value:

The value parameter in the TextArea method refers to the initial content or value to be displayed inside the <textarea> element. This could be a predefined string or some dynamic data you want to show to the user when the form is rendered.

For example: @Html.TextArea(“Description”, “Default text”)
Here, “Default text” is the value that will be pre-populated in the <textarea>. When the page is rendered, this text will appear inside the textarea box, and the user can modify it as needed.

htmlAttributes:

The htmlAttributes parameter allows you to specify additional HTML attributes that will be applied to the generated <textarea> element. This can include attributes like CSS classes, inline styles, placeholder, id, and more. It is passed as an anonymous object, where each property corresponds to an HTML attribute.

For example: @Html.TextArea(“Description”, “Default text”, new { @class = “form-control”, @placeholder = “Enter your description here”, @id = “descriptionTextArea” })
In this case:

  • @class = “form-control”: Adds a CSS class form-control to the textarea for styling.
  • @placeholder = “Enter your description here”: Adds placeholder text.
  • @id = “descriptionTextArea”: Sets the id attribute of the textarea.
Example to Understand TextArea HTML Helper Method in ASP.NET Core MVC

Let’s see an example of the TextArea HTML Helper Method in the ASP.NET Core MVC Application. First, modify the Employee Model, as shown below.

namespace HTML_HELPER.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string? EmployeeName { get; set; }
        public string? Password { get; set; }
        public string? Gender { get; set; }
        public string? City { get; set; }
        public decimal Salary { get; set; }
        public string? Address { get; set; }
    }
}

Next, modify the Home Controller as shown below:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Employee emp = new Employee()
            {
                EmployeeId = 1,
                Address = "Andheri, Sakinaka, Mumbai, 400097, Maharashtra, India"
            };
            return View(emp);
        }
    }
}
Modify the Index View:

Copy and paste the following code into the Index view

@model HTML_HELPER.Models.Employee
@{
    ViewData["Title"] = "Home Page";
}

<label for="Address">Address</label>

@Html.TextArea("Address", null, new { @class = "form-control" })

If you inspect the text area, then you will see that it will produce the following HTML

<textarea class=”form-control” id=”Address” name=”Address”>Andheri, Sakinaka, Mumbai, 400097, Maharashtra, India</textarea>

In the above example, the first parameter is the “Address” property of the Employee model class, which will be set as the name and id of the textarea. The second parameter is the value to display in the textarea, which is null in the above example because the TextArea() method will automatically display a value of the Address property in the textarea. The third parameter will be set as a class attribute. The HtmlAttributes parameter is an object type so it will be an anonymous object, and the attribute name will be its properties starting with @ symbol.

We can also specify any name for the textarea. However, it will not be bound to a model.

@model HTML_HELPER.Models.Employee
@{
    ViewData["Title"] = "Home Page";
}

<label for="MyTextArea">Address</label>

@Html.TextArea("MyTextArea", null, new { @class = "form-control" })

It will produce the HTML: <textarea class=”form-control” id=”MyTextArea” name=”MyTextArea”>This is value</textarea>

If you want, then you can also specify the rows and cols size of the text area as follows:

@Html.TextArea(“MyTextArea”, “This is value”, new { @class = “form-control”, @rows = “4”, @cols = “20”})

In this example:

  • MyTextArea is the name of the text area which will be used in the form submission.
  • new { @class = “form-control”, @rows = “4”, @cols = “20” } is an object initializer that sets HTML attributes like class, rows, and columns for the TextArea.
Example to Understand TextAreaFor HTML Helper Method in ASP.NET Core MVC:

The TextAreaFor helper is specifically designed to work with the model properties efficiently. Let us see an example of the TextAreaFor HTML Helper Method in the ASP.NET Core MVC Application. Copy and paste the following code into the index view.

@model HTML_HELPER.Models.Employee
@{
    ViewData["Title"] = "Home Page";
}

<label for="Address">Address</label>

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

It will produce the following HTML

<textarea class=”form-control” id=”Address” name=”Address”>Andheri, Sakinaka, Mumbai, 400097, Maharashtra, India</textarea>

In the above example, the first parameter in the TextAreaFor() method is a lambda expression that specifies the model property to be bound with the textarea element. In our example, we specified the Address property. So, it generates the input type <textarea> element with id and name property set to the property name Address. The value of the Text Area will be set to the value of the Address property. If you want, then you can also specify the rows and cols size of the text area as follows:

@Html.TextAreaFor(m => m.Address, new { @class = “form-control”, @rows = “4”, @cols = “20”})

In this example:

  • model => model.Address is a lambda expression indicating the model property that the text area is bound to.
  • new { @class = “form-control”, @rows = “4”, @cols = “20”} is an anonymous object that specifies HTML attributes for the <textarea> element. In this case, it assigns a CSS class for styling and sets the number of rows to 5 and the number of cols to 20, determining the text area’s height and width.
What are the Differences Between Html.TextArea and Html.TextAreaFor in ASP.NET Core MVC?

The primary difference between TextArea and TextAreaFor in ASP.NET Core MVC lies in how they bind to model properties and handle data. The following is a detailed explanation of the differences between these two helper methods.

Binding to Model
Html.TextArea:

Html.TextArea is not strongly bound to a model property. It requires you to manually provide the name and value for the <textarea> element. It can be used independently of a model, and it only operates on the data you pass to it.
Example: @Html.TextArea(“Description”, “Enter your description”).
This creates a <textarea> element with a name attribute of “Description” and an initial value of “Enter your description”. There is no connection between this field and any model property.

Html.TextAreaFor:

Html.TextAreaFor is strongly typed and binds directly to a model property. This helper method is part of the strongly typed HTML helpers and is typically used in forms that are bound to a model. It automatically populates the <textarea> with the value of the bound model property and updates the property based on user input during form submission.

Example:
@model YourNamespace.YourModel
@Html.TextAreaFor(model => model.Description)
Here, TextAreaFor generates a <textarea> element that is bound to the Description property of the model. If the model’s Description property contains a value, it will be automatically populated in the textarea.

Model State and Validation
  • Html.TextArea: Since Html.TextArea is not tied to a model, it does not automatically reflect model validation errors or state changes. You need to manually handle validation and error messages.
  • Html.TextAreaFor: Html.TextAreaFor works with model validation, meaning it automatically displays any model validation error messages for the bound property if they exist. It also repopulates the field with the user’s input when validation fails, ensuring that data is not lost during form submissions.
Strongly Typed vs Loosely Typed
  • Html.TextArea: This is loosely typed, meaning it doesn’t enforce any model type checking and works purely based on the string name you provide. There’s no compile-time checking of property names, so you could easily introduce bugs by misspelling the field name.
  • Html.TextAreaFor: This is strongly typed, meaning it is directly tied to a model property, and there’s compile-time checking for the property name. This ensures that if the property name changes or is removed, you will get a compile-time error, making it safer and less error-prone.
IntelliSense and Auto-completion
  • Html.TextArea: It lacks the IntelliSense benefits for model properties, as it does not use lambda expressions, which can lead to more manual errors and slower development.
  • Html.TextAreaFor: Benefits from IntelliSense in IDEs, offering auto-completion for model properties, which speeds up development and reduces errors.
Usage
  • Html.TextArea: This is often used in scenarios without a model or when dynamically creating form fields and working with strongly typed data is not possible.
  • Html.TextAreaFor: This is typically used when working with forms bound to models. It’s useful for easily binding form inputs to a model and ensuring automatic data binding and validation handling.

So, TextArea is useful when you need simple, standalone text areas. In contrast, TextAreaFor is preferred when working with models in ASP.NET Core MVC applications for strongly typed data binding and validation.

In the next article, I will discuss How to Generate A DropDownList using HTML Helper in the ASP.NET Core MVC Application. In this article, I explain How to Create a Text Area using HTML Helper Methods in the ASP.NET Core MVC application. I hope you enjoy this article on generating text area using the HTML helper methods in the ASP.NET Core MVC.

Leave a Reply

Your email address will not be published. Required fields are marked *