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.
  • HTML and CSS: In HTML, a single-line TextBox is created using the <input type=”text”> tag, while a multiline TextBox uses the <textarea></textarea> tag. These can be styled with CSS to match the design of the web application.
  • Attributes: TextBoxes can have various attributes to control their behavior and appearance, such as placeholder for displaying hint text, readonly to make the TextBox display-only, and maxlength to limit the number of characters a user can input.
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 the ASP.NET Core MVC, we can use two different 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 you want to specify the name of the form field manually, while 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:

The TextBox HTML Helper in ASP.NET Core MVC is a server-side helper method that renders an HTML input element of type text. It is used within Razor views to generate HTML markup for a text box where users can input text. 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 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; }
    }
}

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 4 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: The HTML helper instance that this method extends. It indicates that it is an extension method that belongs to the IHtmlHelper class.
  • expression: The name of the form field. Expression name, relative to the current model.
  • value: The value of the text input element. If non-null, the value is to be included in the element.
  • format: A string that is used to format the input. The format string is used to format the “value” attribute unless it comes from model binding.
  • htmlAttributes: An object that contains the HTML attributes for the element.

Returns: It returns a new IHtmlContent containing the <input> element of type text.

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";
    Layout = null;
}

@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. This should match the property’s name in your model if you are binding to a 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” />

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, enabling the framework to handle data display, data posting, and validation feedback for the associated property automatically. The TextBoxFor() HTML Helper Method has 3 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: The IHtmlHelper instance that this method extends.
  • expression: An expression to be evaluated against the current model.
  • format: A string that is used to format the input. The format string is used to format the expression value in the “value” attribute.
  • htmlAttributes: An object that contains the HTML attributes for the element.
Type parameters:
  • TModel: The type of the model.
  • TResult: The type of expression results.

Returns: It returns a new IHtmlContent containing the <input> element whose type attribute is set to “text”.

Example to understand the TextBoxFor() HTML Helper Method:

The Html.TextBoxFor method is used with a lambda expression that specifies the model property to which to bind. This approach is strongly typed and helps prevent errors due to typos in property names. Copy and paste the following code into Index.cshtml view.

@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.

What are the Differences Between Html.TextBox and Html.TextBoxFor in ASP.NET Core MVC?

In ASP.NET Core MVC, both Html.TextBox and Html.TextBoxFor are HTML helpers that generate an HTML <input type=”text”> element. The following are the key differences between Html.TextBox and Html.TextBoxFor:

Syntax and Usage
  • TextBox: This helper is used to specify the name of the form field as a string. It does not provide strong typing and compile-time checking since the field name is specified as a string. Syntax: @Html.TextBox(“fieldName”, (object)value, (object)htmlAttributes).
  • TextBoxFor: This helper uses a lambda expression to specify the form field, offering strong typing and compile-time checking. It is tied directly to a model property. Syntax: @Html.TextBoxFor(model => model.Property, (object)htmlAttributes).
Strong Typing
  • TextBox is not strongly typed. The input field’s name is provided as a string, which means you lose the benefits of compile-time checking. Mistyping the field name results in a runtime error, not a compile-time error.
  • TextBoxFor is strongly typed. It uses a lambda expression to refer to the model property directly, ensuring that any changes to the property name are reflected at compile time, thus reducing the risk of errors.
Model Binding
  • TextBox requires manual association with model properties. Since it uses a string to identify the field, you need to ensure it matches the model property name so it binds correctly.
  • TextBoxFor automatically binds to the model property specified in the lambda expression, making it easier to maintain and refactor code as the model changes.
IntelliSense and Refactoring
  • TextBox 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.
  • TextBoxFor, being strongly typed, supports IntelliSense in the lambda expression and is automatically updated during refactoring, which helps maintain code integrity.
Use Cases
  • TextBox might be preferred in scenarios where the form field does not directly correspond to a model property, when dynamic field names are required or when you require more flexibility in specifying the form field’s name.
  • TextBoxFor is generally preferred for most use cases, especially when working with strongly typed views and models, as it ensures type safety, reduces errors, and improves developer productivity through IntelliSense and refactoring support. So, use Html.TextBoxFor for model-driven forms where you want strong typing, automatic model binding, and validation. It ensures that your view is tightly coupled with your model, making your code more maintainable and less error-prone.

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 *