TextBox HTML Helper in ASP.NET Core MVC

TextBox HTML Helper in ASP.NET Core MVC

In this article, I will discuss the TextBox HTML Helper Method in ASP.NET Core MVC Web Application with Examples. Please read our previous article discussing the basic concepts of HTML Helpers in ASP.NET Core MVC Applications.

What is TextBox in Web Application?

A TextBox in web applications is a form element that allows users to input text data. It’s a basic yet essential component in creating web forms, enabling the collection of information from users. TextBoxes can be used for various purposes, such as entering names, email addresses, passwords, search queries, and other data. Here are some key points about TextBoxes in web applications:

  • Single-line TextBox: The most common type of TextBox allows users to input a single line of text. It’s used for short text inputs like names, email addresses, or search terms.
  • Multiline TextBox: A multiline TextBox or textarea can be used for longer inputs, such as comments or messages. This type of TextBox allows for the input of text across multiple lines.
How Do We Create TextBox using HTML Helper in ASP.NET Core MVC?

To create a TextBox using the HTML Helper Method in the ASP.NET Core MVC Application, we need to use the TextBox Helper method. In ASP.NET Core MVC, the TextBox HTML Helper creates a <input> element of type text. It is typically used to render text input fields in a form. In the ASP.NET Core MVC, we can use two types of TextBox Helper methods to generate a textbox in a Razor view. These two extension methods are TextBox() and TextBoxFor().

The Html.TextBox method is used when we want to specify the form field’s name manually. On the other hand, the Html.TextBoxFor is used with model properties, providing a strongly typed approach. That means the TextBox() HTML Helper method is loosely typed, whereas the TextBoxFor() HTML Helper method is strongly typed.

Example to Understand TextBox HTML Helper in ASP.NET Core MVC:

Let us understand how to create a text box using the TextBox Helper method with an example. First, create a new ASP.NET Core Web Application using the Model-View-Controller Project template named HTML_HELPER.

Creating Employee Model:

Once you create the project, create a class file with the name Employee.cs within the Models folder and then copy and paste the following code into it.

namespace HTML_HELPER.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Password { get; set; }
        public string? Gender { get; set; }
        public string? City { get; set; }
        public decimal Salary { get; set; }
        public DateTime? DateOfBirth { get; set; }
    }
}

We will use the above Employee model with TextBox() and TextBoxFor() HTML Helper methods.

Modifying Home Controller:

Modify the Home Controller as follows. The HomeController is created with one action method, i.e., the Index action method.

using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
TextBox() HTML Helper Method in ASP.NET Core MVC:

The Html.TextBox() Helper method creates an element of <input type=”text”> with specified name, value, and HTML attributes. There are four overloaded versions of this Html.TextBox() Helper method is available, as shown in the image below. The following methods are loosely typed methods.

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

Parameters:
  • htmlHelper: This is the instance of IHtmlHelper that provides access to the TextBox method and other HTML helpers in Razor views. It is implicitly available in Razor views (e.g., as @Html) and is used to generate HTML elements dynamically. You do not pass this manually; it’s always available as the helper context.
  • expression: In the TextBox helper method, the expression refers to the input field’s name. This string represents the name and id attributes of the <input> element. It tells the helper the input element’s name, which is essential for model binding when posting data back to the controller.
  • value: This parameter is the initial value the input field will display when rendered. It populates the <input> element with a value. It provides a way to pre-fill the input field, such as when editing a form with existing data.
  • format: This optional parameter specifies how the value should be formatted when rendered in the input field. It is typically used to format dates, numbers, or other values requiring a specific display format. It ensures that the value is displayed in a specific format (e.g., date or currency formatting) that might differ from how it is stored in the model.
  • htmlAttributes: This parameter allows you to specify additional HTML attributes for the <input> element, such as CSS classes, IDs, placeholders, etc. It is passed as an anonymous object. It customizes the appearance and behavior of the input field by adding attributes like class, id, maxlength, etc.
Modifying the Index View:

Please modify the Index View of the Home Controller as shown below to use the TextBox Helper method.

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

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

Here in @Html.TextBox(“EmployeeName”, null, new { @class = “form-control” })

  • EmployeeName: The name of the input element. If you are binding to a model, this should match the property’s name in your model.
  • null: This is where you can specify the value of the TextBox. Passing null means, it will be empty by default or filled with data from the model if the name matches.
  • new { @class = “form-control”}: This anonymous object contains HTML attributes for the TextBox. In this example, it sets the CSS class.

Run the application and view the page source. The textbox will be produced using the following HTML.

<input class=”form-control” id=”EmployeeName” name=”EmployeeName” type=”text” value=”” />

In the above example, the first parameter is EmployeeName, a property of the Employee model that will be set as the name and id of the textbox. The second parameter is the value that we need to display in the textbox, which is null in the above example because the TextBox() method will automatically display the value of the EmployeeName property of the Employee model. The third parameter will be set as the class attribute. The HTML attributes parameter is an object type so that it can be an anonymous object, and the attributes name will be its properties starting with @ symbol.

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

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

It will produce the following HTML

<input class=”form-control” id=”myTextBox” name=”myTextBox” type=”text” value=”This is value” />

You can also apply the format parameter to specify how to display the data. For example, modify the Index.cshtml view as follows. Here, we display the date time values in yyyy-MM-dd format.

@{
    ViewData["Title"] = "Home Page";

    // Hardcoded DateTime value
    var hardcodedDate = new DateTime(2024, 8, 20);

    // Format the DateTime value to a specific format
    var formattedDate = hardcodedDate.ToString("yyyy-MM-dd"); // Change format as needed
}

@Html.TextBox("DateOfBirth", hardcodedDate, formattedDate, new { @class = "form-control", placeholder = "Enter your birth date" })
TextBoxFor() HTML Helper Method in ASP.NET Core MVC Application:

The TextBoxFor() HTML helper is a strongly typed HTML helper method in ASP.NET Core MVC that generates a text input element for a form. This helper method binds a model property to a text box, automatically enabling the framework to handle data display, posting, and validation feedback for the associated property. The TextBoxFor() HTML Helper Method has three overloaded versions available in ASP.NET Core MVC, as shown in the image below.

TextBoxFor() HTML Helper Method in ASP.NET Core MVC Application

Parameters:
  • htmlHelper: This refers to the instance of IHtmlHelper, which is used to call the TextBoxFor method. It is implicitly available in Razor views as @Html. It provides access to helper methods, such as TextBoxFor, that generate HTML based on the model’s properties and enable interaction between the model and view.
  • expression: This is a lambda expression that identifies the model property the TextBoxFor helper will bind to. It defines which model property will generate the <input> element. The expression allows automatic data binding between the form’s input field and the model’s property, ensuring that data from the form is correctly bound back to the model when submitted.
  • format: This optional parameter specifies the format in which the value of the bound model property should be displayed in the input field. It is commonly used for formatting dates, numbers, or other data types. The format ensures that the value of the bound property is displayed in a user-friendly or standardized way, such as formatting a date to MM/dd/yyyy or a number to a currency format.
  • htmlAttributes: This parameter allows you to pass additional HTML attributes to the generated <input> element, such as class, id, placeholder, etc. It is passed as an anonymous object. The htmlAttributes parameter customizes the appearance and behavior of the input field by allowing you to set CSS classes, add a placeholder, specify the field’s maximum length, etc.
Example to understand the TextBoxFor() HTML Helper Method:

Please modify the Index View of the Home Controller as shown below to use the TextBoxFor Helper method. Here, we are creating HTML_HELPER.Models.Employee model.

@model HTML_HELPER.Models.Employee
@Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })

Here,

  • model => model.EmployeeName: A lambda expression that specifies the property of the model to which this TextBox is bound.
  • new { @class = “form-control” }: Similar to the Html.TextBox example sets the HTML attributes for the TextBox.

Run the application and inspect the element, and you will see that it will produce the following HTML

<input class=”form-control” id=”EmployeeName” name=”EmployeeName” type=”text” value=”” />

In the above example, the first parameter in TextBoxFor() HTML Helper Method is a lambda expression that specifies the EmployeeName property of the Model object to bind with the textbox. It generates an input-type text element with id and name property, and the property’s value is set to EmployeeName. The value attribute will be set to the value of the EmployeeName property of the Model Object.

You can also apply the optional format parameter to specify how to display the data. For example, modify the Index.cshtml view as follows. Here, we display the date-time values in yyyy-MM-dd format.

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

@Html.TextBoxFor(model => model.DateOfBirth, "{0:yyyy-MM-dd}", new { @class = "form-control", placeholder = "Enter Date of Birth" })
What are the Differences Between Html.TextBox and Html.TextBoxFor in ASP.NET Core MVC?

The following are the key differences between Html.TextBox and Html.TextBoxFor:

Model Binding
  • Html.TextBox: It is not strongly typed and does not bind directly to a model’s property. Instead, we need to specify the field’s name as a string used to generate the <input> element. It is more generic and flexible but requires manual handling for model binding. Example: Html.TextBox: @Html.TextBox(“FirstName”, “John”)
  • Html.TextBoxFor: It is strongly typed and binds directly to a specific model property using a lambda expression. It automatically connects the form field to the property in the model, making data binding more convenient and less error-prone. Example: Html.TextBoxFor: @Html.TextBoxFor(model => model.FirstName)
Type Safety
  • Html.TextBox: Since it takes the field name as a string, it is not type-safe. You can accidentally misspell the field name, and this error will only be caught at runtime. Example: “FirstName” is a string that could have typographical errors.
  • Html.TextBoxFor: Being strongly typed, it is type-safe. The lambda expression refers directly to a model property, so any issues will be caught at compile time. Example: model => model.FirstName references the model’s FirstName property directly and ensures its existence.
Automatic Binding
  • Html.TextBox: You have to manually specify the field name, value, and other attributes. You are responsible for ensuring that the value is properly populated and displayed in the field. Example: @Html.TextBox(“FirstName”, Model.FirstName)
  • Html.TextBoxFor: It automatically populates the input field with the value of the specified model property. The value is automatically bound back to the model property when the form is submitted. Example: @Html.TextBoxFor(model => model.FirstName)
Usage in Strongly Typed Views
  • Html.TextBox: Can be used in both strongly typed and non-strongly typed views because it doesn’t depend on the model. You explicitly set the name, value, and other attributes.
  • Html.TextBoxFor: This is primarily used in strongly typed views where you have a model and want to bind input fields to the properties of the model.
IntelliSense and Refactoring
  • Html.TextBox: It does not support IntelliSense for the field names since they are just strings. Refactoring tools will not update these strings if the associated model property changes.
  • Html.TextBoxFor: TextBoxFor, being strongly typed, supports IntelliSense in the lambda expression and is automatically updated during refactoring.

In the next article, I will discuss the Text Area HTML helper in the ASP.NET Core MVC application. In this article, I try to explain how to create a text box using HTML helper methods in the ASP.NET Core MVC application. I hope you enjoy this article on generating text Boxes using HTML helper methods in the ASP.NET Core MVC.

2 thoughts on “TextBox HTML Helper in ASP.NET Core MVC”

Leave a Reply

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