TextBox HTML Helper in ASP.NET Core MVC

TextBox HTML Helper in ASP.NET Core MVC

In this article, I am going to discuss TextBox HTML Helper Method in ASP.NET Core MVC Web Application with Examples. Please read our previous article before proceeding to this article, where we discussed the basic concepts of HTML Helpers in ASP.NET Core MVC Application.

How to Create TextBox using HTML Helper in MVC?

To create a TextBox using 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 view. Those two extension methods are TextBox() and TextBoxFor(). The TextBox() HTML Helper method is loosely typed, whereas the TextBoxFor() HTML Helper method is strongly typed.

What is TextBox HTML Helper in ASP.NET Core MVC?

The TextBox HTML Helper in ASP.NET Core MVC is used to generate an HTML <input> element of type “text”. It’s commonly used for capturing single-line text input from users, such as names, addresses, or other short pieces of information. The TextBox HTML Helper also supports model binding, simplifying associating the input with a model property.

How to Create TextBox using 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 with the name HTML_HELPER.

Creating Employee Model:

Once you create the project, then 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 are going to 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 below image. 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 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, value to include in the element.
  • format: A string that is used to format the input. The format string is used to format the “value” attribute unless that came 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;
}

Run the application and view the page source, and you will see that it will produce the following HTML for the textbox.

<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 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 method is a strongly typed extension method. It generates an element of <input type=”text”> for the model property, which must be specified using a lambda expression. The TextBoxFor() HTML Helper method binds the specified model object property to the input element. So, it automatically displays that model property value within the textbox. The TextBoxFor() HTML Helper Method has 3 overloaded versions available in ASP.NET Core MVC, as shown in the below image.

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:

Copy and paste the following code into Index.cshtml view

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

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.

TextBox HTML Helper can simplify the process of creating text input fields in our ASP.NET Core MVC views. It ensures that your input fields are properly associated with model properties, supports model binding, handles validation, and provides consistency in your form elements.

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

As we already discussed that the @Html.TextBox() is a loosely typed helper method, whereas the @Html.TextBoxFor() is a strongly typed helper method.

The Html.TextBox() Helper method is not strongly typed; hence, they don’t require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor() HTML Helper method is a strongly typed method; hence, it requires a strongly typed view, and the name should be given using the lambda expression.

The Strongly typed HTML helper methods also provide compile-time error checking. We mostly prefer strongly typed HTML Helper methods in real-time applications.

But the most important point we need to remember is whether we use Html.TextBox Helper method or Html.TextBoxFor() Helper method, the end result is the same; they generate the same HTML.

In ASP.NET Core MVC, both Html.TextBox and Html.TextBoxFor is an HTML Helper method used to generate HTML <input> elements of type “text” for capturing single-line text input from users. However, they have distinct differences in terms of how they are used and the scenarios in which they are appropriate. Let’s compare Html.TextBox and Html.TextBoxFor:

Html.TextBox:

The Html.TextBox method is a basic HTML Helper that directly generates an <input> element with a specified name and value. It’s often used when you need to generate a text input field without the need for strongly typed model binding. It gives you more manual control over the attributes of the input element.

Example usage of Html.TextBox:

@Html.TextBox("EmployeeName", null, new { @class = "form-control", placeholder = "Enter Name" })
Html.TextBoxFor:

The Html.TextBoxFor method, on the other hand, is a more powerful HTML Helper that’s part of the model binding infrastructure. It generates an <input> element associated with a model property. This method is used when you want to create a text input field that is automatically associated with a property of your model, making it easier to capture and bind data during form submission.

Example usage of Html.TextBoxFor with model binding:

@model HTML_HELPER.Models.Employee
@Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control", placeholder = "Enter Name" })
Key Differences Between Html.Text and Html.TextBoxFor:
Model Binding:
  • Html.TextBox: This does not provide automatic model binding. You need to manually retrieve the content of the <text> from the Request.Form collection during form submission.
  • Html.TextBoxFor: Provides automatic model binding. The input’s value will be bound to the corresponding property in the model when the form is submitted.
Strongly Typed:
  • Html.TextBox: Not strongly typed. You specify the input’s name as a string, which can lead to potential naming conflicts and mismatched names during form submission.
  • Html.TextBoxFor: Strongly typed. The input’s name is automatically generated based on the property expression provided, ensuring accurate model binding.
Code Refactoring and Safety:
  • Html.TextBox: This can lead to runtime errors if the input’s name does not match the expected property name. Prone to typos and naming conflicts.
  • Html.TextBoxFor: Reduces the chance of runtime errors, as the input’s name is generated from the property expression.
Validation:
  • Html.TextBox: Does not inherently handle model validation attributes.
  • Html.TextBoxFor: Automatically renders validation attributes based on model validation attributes (e.g., [Required]).
Code Maintenance and Readability:
  • Html.TextBox: More manual and less readable, especially when dealing with complex views and models.
  • Html.TextBoxFor: More readable and maintainable, especially when working with strongly typed views and models.

The Html.TextBoxFor is typically the preferred choice when you’re working with models and want to take advantage of model binding, automatic validation, and cleaner code. Html.TextBox can be used when you need more manual control over input generation and don’t require the benefits of model binding.

In the next article, I am going to discuss the Text Area HTML helper in the ASP.NET Core MVC application. Here, 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 How to Generate Text Box using the HTML Helper Methods in ASP.NET Core MVC article.

Leave a Reply

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