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?

A TextArea in a web application refers to a user interface 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?

The TextArea HTML Helper generates a multi-line text input field, which is useful for inputs that require longer text from the user, such as comments or descriptions. To create TextArea using the HTML Helper in the ASP.NET Core MVC application, we need to use the TextArea Helper methods. The IHtmlHelper class provides two extension methods to generate the textarea, i.e., multiline textbox in a razor view: 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 in ASP.NET Core MVC is a server-side helper method used to generate a multi-line <textarea> HTML element with a specified name, value, and HTML attributes. It is part of the ASP.NET Core MVC framework and is used within Razor view files to create a text area in your forms dynamically. This helper is specifically designed to work with model properties, making it easier to collect or display multi-line text input from the user. Here’s a brief overview of its purpose and how it’s typically used:

  • Data Entry: Allows users to enter multiple lines of text, such as comments, descriptions, or any information that requires more space than a single-line text box.
  • Model Binding: Seamlessly binds to model properties, ensuring that data entered by the user can be easily collected and processed on the server side. This is particularly useful for handling form submissions.
  • HTML Attributes: Supports adding custom HTML attributes, such as CSS classes, styles, placeholder text, etc., making it flexible for various styling and functionality needs.

The TextArea() HTML Helper method is a loosely typed helper method because the name parameter is a string. The name parameter can also be the name of a model object’s property. It binds the specified property with the textarea. As a result, it automatically displays that property value within the textarea. There are 4 overloaded versions available for TextArea() HTML Helper Method in ASP.NET Core MVC, as shown in the image below.

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

Parameters:
  • htmlHelper: The HTML helper instance that this method extends.
  • expression: Expression name relative to the current model.
  • value: If non-null, value to include in the element.
  • htmlAttributes: An object that contains the HTML attributes for the element.

Returns: Returns the IHtmlContent element with the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes.

Example to Understand TextArea HTML Helper Method in ASP.NET Core MVC

Let us see an example of the TextArea HTML Helper Method in the ASP.NET Core MVC Application. Let’s 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
@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.

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

It will produce the following 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.
TextAreaFor() HTML Helper Method in ASP.NET Core MVC:

The TextAreaFor helper is specifically designed to work within the MVC (Model-View-Controller) pattern, allowing developers to bind textarea elements in their views to model properties easily. This binding facilitates the automatic population of form fields when displaying a view and the straightforward capture of user input when a form is submitted.

Here is a basic overview of how the TextAreaFor helper is used: @Html.TextAreaFor(model => model.PropertyName, new { htmlAttributes = new { @class = “form-control” } })

  • model => model.PropertyName is a lambda expression where the model represents the model passed to the view. PropertyName should be replaced with the actual property name in the model you want to bind to the textarea.
  • new { htmlAttributes = new { @class = “form-control” } } is an optional parameter where you can specify HTML attributes for the textarea element. In this example, the textarea is assigned a CSS class form-control.

Key features and benefits of using TextAreaFor include:

  • Strongly Typed: It provides compile-time checking of the property names, reducing errors.
  • Model Binding: It automatically binds the textarea to a model property, making it easy to display or update data.
  • HTML Attributes: Developers can easily add HTML attributes to customize the appearance and behavior of the textarea.
  • Razor Syntax: TextAreaFor uses Razor syntax, making it concise and easy to integrate within views.
Example to Understand TextAreaFor HTML Helper Method in ASP.NET Core MVC:

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
@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 textarea 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, number of cols to be 20 determining the text area’s height and width.
What are the Differences Between Html.TextArea and Html.TextAreaFor in ASP.NET Core MVC?

In ASP.NET Core MVC, both Html.TextArea and Html.TextAreaFor are HTML helper methods used to render a <textarea> HTML element in a view. Despite their similarities in rendering text areas, there are key differences primarily related to how they are used and their binding behavior with model properties.

Html.TextArea in ASP.NET Core MVC
  • General Usage: Html.TextArea is a more general HTML helper method that requires you to specify the name of the form field manually. It does not bind directly to a model property.
  • Syntax: @Html.TextArea(“name”, “value”, new { htmlAttributes })
  • Flexibility: Provides more flexibility in specifying the name of the textarea element, making it suitable for scenarios where you might not be binding directly to a model property.
  • Model Binding: Since it doesn’t bind to a model property directly, you are responsible for manually handling the retrieval and setting of values, which could be more error-prone in complex forms.
Html.TextAreaFor in ASP.NET Core MVC
  • Model Binding: Html.TextAreaFor is a strongly typed HTML helper method that binds directly to a specified property on the model. This direct binding facilitates automatic value retrieval and assignment based on the model’s property, making it more robust for data entry and editing scenarios.
  • Syntax: @Html.TextAreaFor(model => model.PropertyName, new { htmlAttributes })
  • Strongly Typed: As a strongly-typed helper, it provides compile-time checking of the property name, reducing the chances of runtime errors due to misspellings or incorrect property names.
  • Convenience: Offers the convenience of automatically handling the value based on the model’s property, making it easier to display or update the text area’s content from the model.
Key Differences Between Html.TextArea and Html.TextAreaFor in ASP.NET Core MVC
  • Type Safety: Html.TextAreaFor provides type safety by ensuring at compile time that the property it is bound to exists on the model. Html.TextArea does not provide such safety since it uses a string to specify the form field name.
  • Model Binding: Html.TextAreaFor automatically binds to a model property, making it easier to handle form submissions and validations related to the property. Html.TextArea requires manual handling of these aspects.
  • Error Handling: The strong typing of Html.TextAreaFor helps catch errors at compile time, whereas Html does not.TextArea, such errors might only be discovered at runtime.
  • Use Case: Use Html.TextArea when you need flexibility or when you are not working directly with a model property. Use Html.TextAreaFor for direct model binding, especially in forms that are strongly tied to model properties for creating or editing data.

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 *