HTML Helpers in ASPCoreMVC
HTML Helpers in ASPCoreMVC
In this article, I will discuss HTML Helpers in ASP.NET Core MVC Applications with Examples. Please
read our previous articles discussing Action Results in ASP.NET Core MVC Applications.
HTML Helpers in ASP.NET Core MVC are methods used in Razor views to generate HTML elements
dynamically. They provide a way to render standard HTML elements programmatically, which helps
reduce the amount of manual HTML code we have to write in our views. HTML Helpers simplify the
process of creating form controls such as textboxes, dropdown lists, checkboxes, radio buttons, and
other HTML elements, especially when bound to model data. They help keep the Razor views cleaner
by encapsulating HTML markup. By using HTML Helpers, developers can render HTML in a strongly
typed, C# centric way. This allows for better reuse and more readable code.
Advertisements
Why HTML Helpers in ASP.NET Core MVC?
HTML Helpers in ASP.NET Core MVC simplify the process of creating HTML elements on a web page
and binding data to them. Using HTML Helpers reduces the chances of introducing typos or errors
when manually writing HTML code. Additionally, HTML Helpers facilitate model binding, validation, and
integration with ASP.NET Core features such as tag helpers, form validation, and data annotations.
They also promote code reusability and maintainability, making views cleaner and easier to manage.
For example, if you want to generate a textbox with id=”firstname” and name=”firstname,” you can
type all the required HTML in a view, as shown below.
<input type=”text” name=”firtsname” id=”firstname” />
However, in ASP.NET Core MVC, you can use the TextBox HTML helper method to generate a text box
as follows.
@Html.TextBox(“firtsname”)
Several overloaded versions of the above TextBox HTML helper method are available, which you can
use according to your requirements. For example, you can use the following overloaded version of the
TextBox helper method to set the value and name.
@Html.TextBox(“firtsname”, “Pranaya”)
At runtime, the above TextBox HTML helper method generates the following HTML
<input id=”firtsname” name=”firtsname” type=”text” value=”Pranaya” />
It is also possible to set the HTML attributes of a text box. If you want to do so, you need to use the
following overloaded version of the TextBox HTML helper method.
@Html.TextBox(“firtsname”, “Pranaya”, new { style = “background-color:Red;
color:White; font-weight:bold”, title=”Please enter your first name” })
Advertisements
Notice that we are passing the HTML attributes title and style to the TextBox helper method as an
anonymous type. Some HTML attributes are reserved keywords, such as readonly, class, etc. If you
want to use these attributes within a Helper method (which is a C# method), you must prefix them
with the @ symbol, as shown in the example below.
@Html.TextBox(“firtsname”, “Pranaya”, new { @class = “redtextbox”,
@readonly=”true” })
1
These helpers generate basic HTML elements such as text boxes, checkboxes, radio buttons, etc.
Examples include
Html.TextBox()
Html.TextArea()
Html.DropDownList()
Strongly Typed HTML Helpers:
These helpers are associated with a specific data model and allow for compile-time checking of model
properties. They use lambda expressions to refer to model properties directly. Examples include:
You can create custom HTML helpers by defining reusable methods to generate specific HTML markup.
These helpers are typically used when you need custom functionality that the built-in helpers do not
provide.
Advertisements
Is it mandatory to use HTML Helpers in ASP.NET Core MVC?
No, using HTML Helpers in ASP.NET Core MVC is not mandatory. Developers can write plain HTML code
directly in Razor views without using HTML Helpers. However, HTML Helpers can make your views
more consistent, concise, and easier to maintain, especially when dealing with forms, model binding,
and data validation. HTML Helpers also provide additional features such as automatic validation
message display and easier data binding to model properties.
Developers can also use libraries like Tag Helpers (introduced in ASP.NET Core), which are more
readable and tend to align more closely with HTML syntax. The choice between HTML Helpers, Tag
Helpers, or plain HTML depends on the developer’s preference, the application’s complexity, and the
project’s specific requirements.
The HTML Helper methods in ASP.NET Core MVC can be categorized based on the types of HTML they
generate. They are as follows:
Generate HTML input elements such as text boxes, checkboxes, radio buttons, etc. Examples include:
Html.TextBox()
Html.CheckBox()
Html.RadioButton()
Display Control Helpers:
Html.Label()
Html.DisplayFor()
Html.DisplayTextFor()
Form Helpers:
Help generate form elements and manage form submissions. Examples include:
Html.BeginForm()
Html.EndForm()
Validation Helpers:
2
Display validation messages related to model validation. Examples include:
Html.ValidationMessageFor()
Html.ValidationSummary()
Link HTML Helpers:
The Link HTML Helpers generate anchor (<a>) tags that create hyperlinks to different pages within
your application. The following are the examples:
Html.ActionLink
Html.RouteLink
Why HTML Helpers in ASP.NET Core MVC?
The primary reason to use HTML Helpers is to maintain a clean and maintainable codebase. HTML
Helpers abstract the HTML generation part from the business logic, making the Razor views cleaner
and more maintainable. The following are the advantages of using HTML Helpers in ASP.NET Core MVC
Applications:
Advertisements
Reusability: Using HTML Helpers, we avoid duplicating HTML code across views, enhancing
code reusability and maintainability.
Model Binding: HTML Helpers simplify the connection between the view and model
properties, ensuring that form fields are correctly bound to data properties. This makes it
easier to work with forms and dynamic data.
Validation: HTML Helpers automatically generate client-side validation for forms based on
data annotations in the model, reducing the need to write manual validation code.
Consistency: Helpers ensure consistent rendering of HTML elements across views, especially
for form fields and controls.
Reduced Errors: Since HTML Helpers are strongly typed (in the case of For helpers), they
reduce the risk of errors by enabling compile-time checking of model properties.
In the next article, I will discuss the TextBox HTML Helper Method in ASP.NET Core
MVC Applications with examples. This article explains the basic concepts of HTML Helpers in ASP.NET
Core MVC applications. I hope you enjoy this HTML Helpers in ASP.NET Core MVC article.
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.
Advertisements
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().
3
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.
Advertisements
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.
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
}
We will use the above Employee model with TextBox() and TextBoxFor() HTML Helper methods.
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
return View();
}
TextBox() HTML Helper Method in ASP.NET Core MVC:
4
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.
Advertisements
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
@{
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.
Advertisements
Run the application and view the page source. The textbox will be produced using the following HTML.
5
<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.
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.
@{
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.
Advertisements
Parameters:
6
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
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
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
@{
The following are the key differences between Html.TextBox and Html.TextBoxFor:
Model Binding
7
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.
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.
Advertisements
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.
8
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.
Advertisements
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.
Advertisements
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.
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.
Advertisements
9
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.
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.
Advertisements
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
}
Next, modify the Home Controller as shown below:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
10
public ActionResult Index()
EmployeeId = 1,
};
return View(emp);
}
Modify the Index View:
Copy and paste the following code into the Index view
@model HTML_HELPER.Models.Employee
@{
<label for="Address">Address</label>
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
@{
<label for="MyTextArea">Address</label>
If you want, then you can also specify the rows and cols size of the text area as follows:
11
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
@{
<label for="Address">Address</label>
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:
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:
12
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.
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.
In this article, I will discuss the DropDownList HTML Helper Method in ASP.NET Core
MVC Application with Examples. Please read our previous article discussing the TextArea HTML
Helper in ASP.NET Core MVC Application.
Advertisements
What is DropDownList in Web Application?
A DropDownList in a web application is a user interface control allowing users to select a single item
from a list of items presented in a dropdown menu. When it is not activated, it shows the currently
13
selected item. When clicked or tapped, it displays a list of options from which the user can select
one. The DropDownList is particularly useful for fields that have a fixed set of options, such as:
Countries
States or regions within a country
Categories or types of items
Settings options that have predefined choices
In HTML, a DropDownList can be created using the <select> element, where each option within the
dropdown is defined using an <option> tag. Here’s a basic example:
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
In this example, the DropDownList allows users to select a country from the list. When a user selects
an option, the value of the <select> element (accessible through JavaScript or on the server side after
form submission) becomes the value of the selected <option>.
To create a DropDownList using the HTML Helper Method in the ASP.NET Core MVC Application, we
need to use the DropDownList Helper method. In ASP.NET Core MVC, the DropDownList HTML Helper
generates an <select> element representing a dropdown list in an HTML form. We can use two
different types of DropDownList Helper methods to generate a textbox in a Razor view. These two
extension methods are DropDownList() and DropDownListFor().
The Html.DropDownList method is used when you want to specify the name of the form field manually,
while Html.DropDownListFor is used with model properties, providing a strongly typed approach. That
means the DropDownList() HTML Helper method is loosely typed, whereas the DropDownList() HTML
Helper method is strongly typed.
Advertisements
Example to Understand DropDownList HTML Helper Method in ASP.NET Core
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
return View();
14
}
}
Modifying the Index.cshtml View:
Modify the Index.cshtml view as follows. The following code will generate a department dropdown
list. The first item in the drop-down list will be Select Department. Here, we have used the Selected
property to true for the IT element, so the “IT” element will be selected by default when the page
loads.
Advertisements
@{
<div class="form-group">
</div>
Understanding the DropDownList Help Method:
The @Html.DropDownList helper method in ASP.NET Core MVC generates a dropdown list in an HTML
form. In our example, we used the following DropDownList Help Method.
Explanation of Parameters
This is the name of the form element that will be generated. The name attribute in HTML is used to
identify form elements when submitting data. In this case, the form will send the selected
department’s value (e.g., “1” for IT, “2” for HR, etc) as the Departments field when submitted.
This is the list of options for the dropdown. Each SelectListItem object represents an item in the
dropdown with the following properties:
15
Text: The text that will be displayed to the user in the dropdown (e.g., “IT”, “HR”, “Payroll”).
Value: The actual value that will be submitted when the user selects this option (e.g., “1” for
IT, “2” for HR, “3” for Payroll).
Selected: A Boolean value indicates whether this option is selected by default. In our case,
“IT” is selected by default because Selected=true is set for the first item.
Advertisements
“Select Department” (optionLabel parameter):
This default text will be shown when no option is selected. This acts as a placeholder for the dropdown
and is displayed as an option that cannot be selected. It encourages the user to select an actual
department. If the user selects no value, this option will be shown in the dropdown.
This is an anonymous object used to specify HTML attributes for the rendered <select> element. In
this case, the form-control class is added to the dropdown to apply Bootstrap styling. You can add
other HTML attributes as needed, such as id, data-* attributes, style, etc., by specifying them inside
this object.
HTML Output
Now, run the application and access the Index Page. The helper method should generate an HTML
<select> element with options corresponding to the list’s items as follows. To see this, please view the
page source code in the browser:
Advertisements
<option value="2">HR</option>
<option value="3">Payroll</option>
</select>
Here,
The downside of hard-coding the DropDownList value within the code is that if we add or remove
departments from the DropDownList, the code must be modified every time. The following are the
limitations of hard-coding the Drop Down List data:
Repetitive Code: If the dropdown options change frequently, we will have to modify the
hardcoded values at every place the dropdown appears in your application. This becomes
error-prone and time-consuming, especially in large applications.
Centralized Management: With hard-coded options, the dropdown values are scattered
across multiple views or controllers, making it difficult to manage centrally. If you need to
update the dropdown options, you would have to find and edit every instance manually.
Dynamic Data: Hardcoding means that the options are static, and you cannot dynamically
generate them based on external data, such as a database or configuration file. For instance, if
departments are stored in a database, you can’t easily pull in new departments without
updating the code.
Don’t Repeat Yourself (DRY): Hardcoding dropdown values violate the DRY principle, a key
principle of software development. This principle states that you should avoid duplicating logic
or data. By hardcoding dropdown lists, you may end up with repeated code across multiple
views, making your application harder to maintain.
16
No Data Validation: When dropdown options are hardcoded, we lose the benefit of validation
against real-time data. For example, a user might select a department that no longer exists in
the database because the dropdown was not updated.
Data Source Mismatch: If you hardcode values but the actual data (e.g., departments,
categories) come from an external source like a database, there’s a risk of mismatches. For
instance, if the department names or IDs change in the database, your hardcoded dropdown
will no longer reflect the correct data, leading to inconsistencies.
Hardcoded Values in Views: Having large hardcoded dropdowns in your views can increase
the size of the HTML rendered, which may affect page load times, particularly for larger
dropdowns or more complex forms.
Inability to Scale: If you want to support more advanced scenarios like filtering or
dynamically preparing the dropdown based on user input or other data sources, hardcoding
will limit these possibilities.
How do you set the Dropdown list values from the database in the ASP.NET Core MVC?
Most of the time, or in real-time applications, we get the data from a database. To understand this,
let’s create a Department Class and then populate the department’s values within the controller. First,
add a class file named Department.cs within the Models folder and then copy and paste the following
code.
namespace HTML_HELPER.Models
}
Modify Home Controller:
Next, modify the Home Controller as follows. We store the list of departments in the ViewBag, which
we will use in the index view. The following code is self-explained, so please read the comment lines
for a better understanding.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
// Typically, data would be fetched from a database, but here we're manually creating a list of
17
new Department() {Id = 2, Name="HR" },
};
// Creating a SelectList for departments, which will be used in the view to generate a dropdown list
// The second argument ("Id") specifies the value that will be submitted when a department is selected
// The third argument ("Name") specifies the display text for each department in the dropdown list
// This will send the model (ViewBag.Departments) to the view for rendering
return View();
}
You can also do the same thing in the following way:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HTML_HELPER.Controllers
// Each SelectListItem has 'Text' for display and 'Value' for the submitted data
// First dropdown item: Displayed as "IT", with a value of "1" when selected
// Second dropdown item: Displayed as "HR", with a value of "2" when selected
};
// Assigning the list of SelectListItem objects to the ViewBag with the key "Departments"
// This makes the dropdown data accessible to the view when rendering the dropdown list
ViewBag.Departments = items;
18
// The ViewBag data (Departments) will be available for use in this view
return View();
}
Modifying the Index View:
Next, modify the Index.cshtml view as follows. In the Index view, access the Department list from
ViewBag.
@{
<div class="form-group">
"form-control" })
</div>
In the above example, the first parameter is the property name for which we want to display the list of
items. The second parameter is the list of values displayed within the DropDownList. Here, we have
used the ViewBag mechanism to get the department values. The third parameter is the label, which is
nothing but the first item in the drop-down list, and the fourth parameter is for the HTML attributes like
CSS to be applied on the drop-down list.
How Do We Use Enum to Set the Dropdown List Values in the ASP.NET Core MVC
Application?
Let’s see how to use Enum to set the Dropdown list values. In this example, we will set the Gender
Values from the enum. So, create a class file named Gender.cs and add the following Gender enum.
namespace HTML_HELPER.Models
Male,
Female,
Other
}
Modifying the Index View:
Next, modify the Index View as follows. The following HTML code is self-explained. Please read the
comment lines for a better understanding.
@{
19
// Sets the title for the page in the ViewData dictionary, which can be accessed by the layout page or
<div class="form-group">
<!-- This is an HTML label element associated with the select dropdown below. The 'for' attribute must
match the 'id' of the select element it labels, improving accessibility -->
<!-- Html.DropDownList is an HTML helper used to generate a dropdown list (select element) -->
@Html.DropDownList("Gender", // The first parameter is the name of the form field. It will also be used
as the 'name' and 'id' attribute of the resulting HTML select element
SelectList. It takes the enum values of 'Gender', providing the data source for the dropdown options
"Select Gender", // The third parameter is the text to display in the default option, which in this case
new { @class = "form-control" } // The fourth parameter is an anonymous object that contains HTML
attributes to be added to the select element. Here, it assigns a Bootstrap class for styling
</div>
Now, run the application and inspect the HTML element, and you will see the following HTML
generated for the drop-down list:
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
If you notice, then you will see it is not included in the Value attribute of the Option tag. This is
because of the default behavior when using Enum.GetValues() with SelectList. In this case, it will use
enum names as both the text and the value in the HTML <option> tags. To specify different values, we
need to manually set up the SelectList to use the enum values (i.e., the underlying integer values of
the enum) instead of the names. So, modify the Index view as follows:
@{
<div class="form-group">
// This SelectList creates the list of options for the dropdown from the Gender enum.
// Enum.GetValues(typeof(Gender)) retrieves all the values of the Gender enum (e.g., Male, Female,
Other).
20
// .Cast<Gender>() converts these values to the Gender enum type.
new SelectList(Enum.GetValues(typeof(Gender))
// Select() is a LINQ method that projects each Gender enum value into a new SelectListItem object.
// For each Gender enum value, we create a SelectListItem with Text and Value properties.
// Text will display the string representation of the enum (e.g., "Male"), and
// Value will store the integer value of the enum, cast to a string (e.g., "1" for Male).
Text = e.ToString(), // The display text for the option (e.g., "Male")
Value = ((int)e).ToString() // The value attribute for the option (e.g., "1")
}),
// "Value" specifies that the dropdown will use the "Value" property of each SelectListItem for the
option values.
// "Text" specifies that the dropdown will display the "Text" property of each SelectListItem.
"Value", "Text"),
// The third argument is a string that sets the default placeholder option.
// This will create an option with an empty value and the text "Select Gender".
"Select Gender",
// This anonymous object specifies additional HTML attributes for the <select> element.
// @class is a reserved keyword, so it's escaped with @ to define the Bootstrap class "form-control".
</div>
This will generate the desired HTML:
<option value="0">Male</option>
<option value="1">Female</option>
<option value="2">Other</option>
</select>
Example to Understand DropDownListFor HTML Helper Method
The DropDownListFor() is an HTML helper method in ASP.NET Core MVC that is used to generate a
<select> element (a drop-down list) for a web page from a model property. This helper is strongly
typed, meaning it is bound to a specific model property and helps display a list of options the user can
select from. Let us understand this with an example. First, modify the Employee.cs class file as
follows:
namespace HTML_HELPER.Models
21
public string EmployeeName { get; set; } = null!;
}
Modify the HomeController:
Next, modify the Home Controller as follows. In the code below, we created a ViewBag property to hold
the list of departments. This ViewBag will render the list of departments on the web page. We have
also created an employee object and set the DepartmentID and Gender. While rendering the Gender
and Department for the Employee, we need to use this DepartmentID and Gender as the default
selected value.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
};
ViewBag.Departments = ListDepartments;
EmployeeId = 1,
EmployeeName = "Pranaya",
Gender = "Male",
DepartmentID = 2
};
return View(emp);
}
Modifying Index.cshtml View:
22
@model HTML_HELPER.Models.Employee
@{
<div class="form-group">
<!--
The DropDownListFor helper binds the selected value to the "Gender" property of the Employee model
The SelectList is created from the Gender enum, generating options based on enum values
-->
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender",
<!--
The DropDownListFor helper binds the selected value to the "DepartmentID" property of the Employee
model
The SelectList is created from the data stored in ViewBag.Departments, which contains department
information
The Id of the department is used as the value, and the Name of the department is displayed
-->
"Select Department",
</div>
In the above example, the first parameter in the DropDownListFor() HTML Helper method is a lambda
expression that specifies the model property to be bound with the select element. We have specified
the Gender and DepartmentID property. The second parameter specifies the items to show in the
dropdown list using SelectList. The third parameter is the option Label, which will be the first item of
the drop-down list.
23
In ASP.NET Core MVC, both Html.DropDownListFor and Html.DropDownList are HTML helper methods
used to create drop-down list elements (<select> tags) in Razor views. However, they differ in how
they bind data to the model and how they are used. The following is a breakdown of their differences:
Model Binding
Html.DropDownListFor:
Html.DropDownList:
Type Safety
24
In this article, I will discuss How to Generate Radio Buttons using RadioButton HTML Helper in
ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to
Generate DropDownList using HTML Helper in ASP.NET Core MVC.
Advertisements
What is RadioButton in Web Application?
A Radio Button in Web Applications is an input element that allows users to select one option from a
predefined set of options. Radio buttons are useful when we want the user to select a single option
from multiple options, where displaying all possible options simultaneously is preferable for a quick
decision. The following are some of the key characteristics of Radio Button in Web Applications:
Mutually Exclusive: Radio buttons are designed to be mutually exclusive, meaning that only
one option can be selected. When a user selects a new option, any previously selected option
within the same group becomes deselected.
Grouping: Radio buttons are grouped using the same name attribute in HTML to enforce
mutual exclusivity. This ensures that they behave as a single unit, and only one option can be
selected within that group.
User Interface: Visually, a radio button appears as a small circle that can be filled or
surrounded by a dot when selected. Unselected radio buttons are empty circles.
State Indicator: When selected, a radio button typically displays a small dot or circle inside it
to indicate the chosen option.
HTML Structure: In HTML, a radio button is represented by an <input> element with a type
attribute set to “radio”. Each radio button within a group should have the same name attribute
and a unique value attribute.
Use Cases: Radio buttons are commonly used when users need to make a single choice from
a predefined set of options, such as selecting a gender or choosing a payment method.
The following is an example that demonstrates the use of radio buttons:
<form>
<label for="age2">18-30</label><br>
<label for="age3">31-45</label><br>
</form>
In this example, users can select their age range from the provided options. Because all radio buttons
share the same name attribute (age), only one of these options can be selected at a time, ensuring a
clear and straightforward selection process.
How Do We Create Radio Buttons Using HTML Helper in ASP.NET Core MVC?
To create a Radio button using the HTML Helper Method in the ASP.NET Core MVC Application, we
need to use the RadioButton Helper method. In the ASP.NET Core MVC, we can use two different types
of RadioButton Helper methods to generate a RadioButton in a Razor view. These two extension
methods are RadioButton() and RadioButtonFor().
Advertisements
The Html.RadioButton method is used when we want to manually specify the form field’s name, while
Html.RadioButtonFor is used with model properties, providing a strongly typed approach. That means
the RadioButton() HTML Helper method is loosely typed, whereas the RadioButtonFor() HTML Helper
method is strongly typed.
25
The RadioButton HTML helper in ASP.NET Core MVC generates HTML radio button inputs within a view.
This helper is useful when you want to present users with mutually exclusive options and let them
choose one. Three overloaded versions are available for the RadioButton() HTML Helper method. They
are as follows:
Advertisements
Parameters:
name: The name of the radio button group used to distinguish it from other inputs. Radio
buttons with the same name will be grouped, allowing only one of them to be selected.
value: The value assigned to the radio button.
isChecked: A Boolean value indicating whether the radio button should be checked by
default.
htmlAttributes: Additional HTML attributes to apply to the radio button (optional), such as
style or class.
Modifying Home Controller:
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
return View();
}
Modifying the Index View:
Next, modify the Index View as follows. The following code is self-explained, so please read the
comment lines for a better understanding.
@{
26
ViewData["Title"] = "Home Page";
<div class="form-group">
<!-- Wraps the radio button and its descriptive text (Male) in a label for better accessibility -->
<label class="form-check-label">
<!--
- "Gender" is the name attribute, grouping this with other inputs with the same name so only one can
be selected.
- "Male" is the value attribute, which will be the value sent when this radio button is selected.
- Adds Bootstrap's "form-check-input" class for styling consistency with Bootstrap forms.
-->
Male <!-- Visible label text for the radio button -->
</label>
</div>
<div class="form-group">
<!-- Similar label structure for the Female radio button -->
<label class="form-check-label">
<!--
- Uses the same "Gender" name, ensuring it is part of the same group as the "Male" radio button.
-->
Female <!-- Visible label text for the radio button -->
</label>
</div>
Now run the application and inspect the generated HTML; then you will see the following HTML
generated for the Radio Buttons:
<div class="form-group">
<label class="form-check-label">
Male
</label>
</div>
<div class="form-group">
<label class="form-check-label">
27
<input class="form-check-input" id="Gender" name="Gender" type="radio" value="Female" />
Female
</label>
</div>
What is RadioButtonFor HTML Helper in ASP.NET Core MVC?
The RadioButtonFor HTML Helper in ASP.NET Core MVC creates a strongly typed radio button input
element that is bound to a property of the model passed to the view. It is similar to the RadioButton
helper but offers the advantage of model binding, which simplifies form submission and validation
when working with a strongly typed view model. The following is the Syntax of the RadioButtonFor
Helper method.
@Html.RadioButtonFor(Expression<Func<TModel, TValue>> expression, object value,
object htmlAttributes)
Advertisements
Parameters:
expression: An expression that identifies the model property to which the radio button is
bound. This expression ensures that the radio button reflects the value of the model property
and that any changes made in the form are updated in the model.
value: The value of the radio button, i.e., what will be sent to the server when this button is
selected.
htmlAttributes: An object that contains additional HTML attributes (e.g., classes, styles, IDs)
that can be applied to the radio button for customization.
Example to Understand RadioButtonFor HTML Helper in ASP.NET Core MVC
Let’s understand RadioButtonFor HTML Helper in ASP.NET Core MVC with an example. First, create two
models. Right-click on the Models folder and add two class files
named Company.cs and Department.cs. Once you create the class files, copy and paste the
following code.
Department.cs
namespace HTML_HELPER.Models
}
Company.cs
namespace HTML_HELPER.Models
28
new Department() {Id = 1, Name="IT" },
};
return ListDepartments;
}
Modifying Home Controller:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
[HttpGet]
//company.SelectedDepartment = 2;
return View(company);
[HttpPost]
if (company.SelectedDepartment <= 0)
else
}
Modifying Index Views:
Next, modify the Index.cshtml view as follows. In the below example, the first parameter in the
RadioButtonFor() HTML Helper method is a lambda expression that specifies the model property to be
bound with the RadioButton element. We have created radio buttons for the SelectedDepartment
29
property in the above example. So, it generates three <input type=”radio”> elements with id and
name set to property name SelectedDepartment. The second parameter is the value sent to the server
when the form is submitted.
Advertisements
@model HTML_HELPER.Models.Company
@{
ViewBag.Title = "Index";
<h2>Home Page</h2>
@using (Html.BeginForm())
<div class="form-group">
<div class="form-check">
<label class="form-check-label">
input" })
@department.Name
</label>
</div>
</div>
<div class="form-group">
</div>
}
Understanding Bootstrap Classes used in the above code:
form-group: Wrapping the entire form content in Bootstrap’s form-group to ensure proper
spacing and layout for form elements.
form-check: Each radio button and label pair is wrapped inside a form-check div, a Bootstrap
class specifically for checkboxes and radio buttons.
form-check-input: This Bootstrap class is applied to the radio buttons to style them
consistently.
form-check-label: The label that accompanies the radio button is styled with this class to
align it properly with the radio button.
Submit button: The submit button is styled with Bootstrap’s btn btn-primary classes to make
it look like a primary action button.
Testing the Application:
Now, run the application and click the Submit button without selecting any department. You will
receive a message stating that you have not selected any department. However, if you choose a
department and click the Submit button, you will see the selected department ID.
In ASP.NET Core MVC, both Html.RadioButton and Html.RadioButtonFor are HTML helper methods used
to create radio button inputs on a form, but they are used in slightly different contexts and have
different benefits. Here’s a breakdown of the key differences between these two methods:
30
Type-Safety and Strong Typing
Html.RadioButtonFor: This method is strongly typed and directly tied to a model property. It
uses lambda expressions to refer to model properties, ensuring compile-time checking. This
reduces errors due to typos or type mismatches because references are checked at compile
time.
Html.RadioButton: This method is not strongly typed and relies on string literals to specify
which model property it is associated with. Since these are only checked at runtime, there is a
greater risk of runtime errors due to misspellings or incorrect property names.
Model Binding
Html.RadioButtonFor: Since it’s strongly typed, it’s automatically bound to the model
property specified in the lambda expression. This ensures that the model binding is
straightforward during form submissions and less prone to errors.
Html.RadioButton: To bind correctly on form submissions, manually ensure that the name
attribute matches the model property name. Mistakes in the “propertyName” can lead to
binding errors.
Default State Handling
Html.RadioButton: We need to explicitly specify whether the radio button should be selected
or not by passing a Boolean value. For example, false indicates that the radio button is not
checked by default.
Html.RadioButtonFor: Automatically checks the radio button that corresponds to the value
of the model’s property. You don’t need to specify the checked state manually, as it is handled
based on the model’s data.
Use Cases
Html.RadioButtonFor: It is ideal for forms that are strongly model-driven where each input
corresponds directly to a model property. It’s especially useful in complex forms, handling
multiple fields to maintain consistency and reduce errors.
Html.RadioButton: It is useful in simpler scenarios where a form might not be directly or
solely bound to a model or where dynamic property names are used. It offers more flexibility in
scenarios where model properties might be generated or determined at runtime.
In the next article, I will discuss Check Box HTML Helper in ASP.NET Core MVC application. In this
article, I explain step-by-step how to create a radio button using HTML Helper in an ASP.NET
Core MVC application with examples. I hope you enjoy this Radio Button HTML Helper in ASP.NET
Core MVC article.
In this article, I will discuss How to Generate Check Boxes using CheckBox HTML Helper in
ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to
Generate Radio Buttons using HTML Helper in ASP.NET Core MVC. At the end of this article,
you will understand multiple real-time examples of using the CheckBox Helper method. We will show
you how to use the CheckBox Helper method to generate single and multiple checkboxes.
Advertisements
What is a Check Box in a Web Application?
A CheckBox in a Web Application is a form input element that allows users to select one or more
options from a set of alternatives. It is typically represented as a small square box that can be checked
(selected) or unchecked (not selected). Checkboxes are used when one or more options can be
selected independently, and submitting the form can proceed with any combination of options
selected or none at all.
Binary State: A checkbox has two possible states: checked and unchecked. When a checkbox
is checked, it usually displays a checkmark or a similar indicator inside the checkbox.
Independent Selection: Checkboxes are independent, meaning each checkbox represents a
separate choice, and multiple checkboxes can be checked simultaneously.
31
The HTML element for creating a CheckBox is <input> with the attribute type=”checkbox”. Each
CheckBox in a form is associated with a specific value, and when the form is submitted, the values of
the checked (selected) CheckBoxes are sent to the server as part of the form data. Here’s a simple
example using CheckBoxes:
<label>
Music
</label>
<label>
Books
</label>
<label>
Sports
</label>
</form>
In this example, users can select their interests in music, books, and sports. When submitted, the form
will send the values of the selected interests to the server. Checkboxes are commonly used for
scenarios where users must indicate their preferences, select multiple items from a list, or
enable/disable certain features or options.
Advertisements
How Do We Create Check Boxes Using HTML Helper in ASP.NET Core MVC?
To create a checkbox using HTML Helpers in ASP.NET Core MVC, we need to use Html.CheckBox or
Html.CheckBoxFor methods within our Razor views. The Html.CheckBox method is used when we want
to specify the form field’s name manually. On the other hand, Html.CheckBoxFor is used with model
properties, providing a strongly typed approach. That means the CheckBox() HTML Helper method is
loosely typed, whereas the CheckBoxFor() HTML Helper method is strongly typed.
The CheckBox HTML Helper is specifically used to generate checkboxes that the user can check or
uncheck. These checkboxes are often used for true/false or yes/no options. The following is the syntax
for using the Checkbox HTML helper in the ASP.NET Core MVC Application.
@Html.CheckBox(“propertyName”, bool isChecked, object htmlAttributes)
Here,
Advertisements
propertyName: The name of the property or field this checkbox is bound to.
isChecked: A boolean value indicating whether the checkbox is checked or not.
htmlAttributes: An anonymous object to set additional HTML attributes for the checkbox
element.
Generate a Single Checkbox using the CheckBox Helper Method:
You can use the CheckBox HTML Helper method to generate a single checkbox. Let us understand this
with an example. In a user registration or profile update form, you might offer users the option to
subscribe to your newsletter. Users can opt into email marketing when they register for an account or
update their profile. First, modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc;
32
namespace HTML_HELPER.Controllers
return View();
[HttpPost]
if(SubscribeToNewsletter)
else
}
Modifying the Index View:
Next, please modify the Index View as follows. The following code is self-explained, so please read the
comment lines for a better understanding.
@{
ViewBag.Title = "Index";
@* Creating a form that will send a POST request to the "UpdateProfile" action method of the "Home"
controller *@
<div class="form-check">
@* A div container with the Bootstrap class "form-check" for styling checkbox input elements in a
consistent way *@
First argument "SubscribeToNewsletter" is the name of the checkbox, which will be used to retrieve
Second argument "false" sets the default value of the checkbox to unchecked.
33
Third argument is an anonymous object that assigns a CSS class "form-check-input" for Bootstrap
styling. *@
Subscribe to newsletter
</label>
@* Label associated with the checkbox, provides descriptive text to the user.
The "for" attribute links the label to the checkbox with the ID "SubscribeToNewsletter". *@
</div>
@* A submit button with Bootstrap styling. When clicked, the form data is sent to the server to the
</form>
Terms and Conditions Agreement using Check Box:
Users are often required to agree to terms and conditions before submitting a form, such as during
user registration, job application, or any transaction. Users cannot proceed with registration or form
submission until they check this box. This checkbox is crucial for obtaining legal consent from users
regarding your terms of service or privacy policy. Let us understand this with an example. First, modify
the Home Controller as follows:
Advertisements
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
return View();
[HttpPost]
if(AcceptTerms)
else
}
Modify the Index View:
34
Next, please modify the Index View as follows. The following code is self-explained, so please read the
comment lines for a better understanding. Here, we are enabling the submit button based on the
current status of the checkbox using jQuery. If the user selects the checkbox, the submit button is
enabled, and when the user deselects the checkbox, the submit button is disabled.
@{
ViewBag.Title = "Index";
<h2>Registration Page</h2>
@* The form sends a POST request to the "Register" action method in the "Home" controller when
submitted. *@
<div class="form-check">
The third argument is an anonymous object that sets the HTML attributes for the checkbox:
</label>
The "for" attribute is linked to the checkbox by its ID, "AcceptTerms", ensuring that clicking the label
</div>
The "disabled" attribute disables the button initially, preventing submission of the form until the terms
are accepted.
The button has an ID "submitBtn" so that its disabled state can be toggled via JavaScript. *@
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
// This function executes when the document is fully loaded and ready.
$('#AcceptTerms').click(function () {
if ($(this).is(':checked')) {
// If the checkbox is checked, it removes the "disabled" attribute from the submit button, enabling it.
$('#submitBtn').removeAttr('disabled');
35
} else {
// If the checkbox is unchecked, it adds the "disabled" attribute back to the submit button, disabling it
again.
$('#submitBtn').attr('disabled', 'disabled');
});
});
</script>
What is CheckBoxFor HTML Helper in ASP.NET Core MVC?
The CheckBoxFor HTML helper in ASP.NET Core MVC is a strongly typed helper method used to
generate a checkbox input element bound to a model property. It provides a more robust and type-
safe way of creating checkboxes, especially with view models. The following is the syntax to use the
CheckBoxFor helper method:
@Html.CheckBoxFor(expression, htmlAttributes)
Parameters
expression: This lambda expression identifies the model property to which the checkbox
should be bound. Typically, this will be a boolean property of the model. The expression should
point to the model’s boolean property, like model => model.AcceptTerms.
htmlAttributes (optional): This parameter allows you to specify additional HTML attributes
for the checkbox element, such as class, id, data-* attributes, etc. You can pass these as an
anonymous object. For example, new { @class = “form-check-input”, @id = “checkboxId” }.
These attributes will be added to the generated <input type=”checkbox”> tag.
Advertisements
Enable/Disable Two-Factor Authentication using CheckBoxFor Helper Method:
On a user security settings page, you can give users the option to enable or disable two-factor
authentication (2FA). This is commonly used in user profile security settings, allowing users to increase
the security of their accounts by enabling or disabling two-factor authentication. Let us understand this
with an example. First, create a class file named SecuritySettingsViewModel.cs within the Models
folder, and then copy and paste the following code. This model has a boolean property, i.e.,
EnableTwoFactorAuth, representing whether two-factor authentication is enabled or disabled for the
user.
namespace HTML_HELPER.Models
}
Modifying Home Controller:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
36
public class HomeController : Controller
//Current Settings
EnableTwoFactorAuth = false
};
return View();
[HttpPost]
if(settings.EnableTwoFactorAuth)
else
}
Modifying Index View:
Next, modify the Index View as follows. The CheckBoxFor helper method binds directly to the
EnableTwoFactorAuth property. The checkbox automatically manages the state of this property,
making it easy to track the user’s preference for two-factor authentication.
@model SecuritySettingsViewModel
@{
ViewBag.Title = "Index";
<div class="form-check">
</label>
</div>
37
<button type="submit" class="btn btn-primary">Save Settings</button>
</form>
Now, run the application and click the Submit button without checking the check box. Notice that you
get a message stating, “You Disabled Two Factor Authentication.” On the other hand, if you check the
check box and then click the Submit button, you will see the “You Enable Two Factor Authentication”
message.
Advertisements
Remember Me Option Example using CheckBoxFor Helper Method:
Users can check the “Remember Me” option on the login page to remain signed in across browser
sessions. This use case is frequent in login forms. Users can choose to have their session remembered
on their device, which provides convenience, especially for frequently used services. Let us
understand this with an example.
First, create a model named LoginViewModel.cs within the Models folder and then copy and paste the
following code. The LoginViewModel contains three properties: UserName, Password, and
RememberMe.
namespace HTML_HELPER.Models
}
Modifying the Home Controller
Next, Create an empty MVC Controller named AccountController with the Controller folder and copy
and paste the following code. The Login actions handle GET and POST requests. The POST action
checks if the model is valid and processes the login, potentially utilizing the RememberMe value to
persist the user’s session.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
[HttpGet]
return View();
[HttpPost]
38
{
if (ModelState.IsValid)
if (model.RememberMe)
return View(model);
}
Creating the Login View
Next, create a view using CheckBoxFor for the “Remember Me” checkbox and input fields for
UserName and Password. So, create the Login.cshtml view and copy and paste the following code.
The form contains input fields for the UserName and Password, and the CheckBoxFor helper binds the
RememberMe property to the checkbox input. Bootstrap classes (form-control, form-check-input, etc.)
style the form.
@model LoginViewModel
@{
ViewData["Title"] = "Login";
<h2>Login Page</h2>
<div class="form-group">
</div>
<div class="form-group">
<label for="Password">Password</label>
</div>
<div class="form-check">
39
<label class="form-check-label" for="RememberMe">
Remember me
</label>
</div>
</form>
Generating Multiple Check Boxes using CheckBoxFor Helper Method:
In ASP.NET Core MVC, you can generate multiple checkboxes using the CheckBoxFor helper method by
binding them to your model’s collection property. Let us understand this with one real-time example.
We will create a scenario where a user selects their preferred programming languages from a list of
options. Once the form is submitted, the selected languages will be displayed. This gives the user an
interactive way to select programming languages of their interest, and upon submission, they can see
a summary of their choices.
A user visits the “SelectLanguages” page, where they see a list of checkboxes, each labeled with a
programming language (e.g., C#, ASP.NET Core, Python, Java, Ruby, C++) as shown in the below
image:
The user selects one or more programming languages by checking the appropriate boxes and submits
the form, as shown in the image below.
40
Once the user clicks on the Submit button, the controller processes the submitted data, filters the
selected languages, and redirects the user to a page displaying their selected languages, as shown in
the image below.
Let us proceed and implement this example step by step in ASP.NET Core MVC Application using the
CheckBoxFor HTML Helper Method.
In this example, we will create a model that contains a list of checkboxes, each representing a
programming language. So, create a class file named ProgrammingLanguagesViewModel.cs within the
Models folder and copy and paste the following code.
namespace HTML_HELPER.Models
}
Create the Controller:
In the controller, we will initialize a list of programming languages and pass the
ProgrammingLanguagesViewModel to the view. So, create an Empty MVC Controller
named LanguageController within the Controllers folder and then copy and paste the following code:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
41
var model = new ProgrammingLanguagesViewModel
};
return View(model);
[HttpPost]
.ToList();
// Do something with the selected languages (e.g., display them on a results page)
ViewBag.SelectedLanguages = selectedLanguages;
}
Create the SelectLanguages View:
In the view, we will loop through the list of LanguageOption items and generate checkboxes for each
programming language. So, create a view named SelectLanguages and copy and paste the following
code.
@model ProgrammingLanguagesViewModel
@{
ViewData["Title"] = "SelectLanguages";
@*
42
The 'asp-action' attribute specifies that the form will submit data to the 'SubmitLanguages' action
The 'method="post"' specifies that the form will use the HTTP POST method to send data to the server.
*@
// A for-loop that iterates over the 'LanguageOptions' list in the bound model
(ProgrammingLanguagesViewModel).
language.
<div class="form-group">
@* This generates a checkbox input element for the 'IsSelected' property of the current
LanguageOption object.
CheckBoxFor is a strongly-typed helper method that binds the checkbox to the 'IsSelected' property.
When the form is submitted, the checkbox state (checked or unchecked) will be sent as part of the
form data.*@
<label>@Model.LanguageOptions[i].LanguageName</label>
It displays the name of the programming language by accessing the 'LanguageName' property of the
@*
This generates a hidden input element for the 'LanguageName' property of the current
LanguageOption object.
HiddenFor is a strongly-typed helper method that binds the hidden input to the 'LanguageName'
property.
This ensures that the programming language's name is also submitted with the form data, even
*@
</div>
</form>
Display the Selected Languages:
After submission, we will display the selected languages on a new view. So, create a view
named SelectedLanguages within the Views/Language folder and copy and paste the following
code.
@model List<string>
@{
ViewData["Title"] = "SelectedLanguages";
43
}
@if (Model.Count == 0)
else
<ul>
<li>@language</li>
</ul>
}
That’s it. We are done with our implementation. Now, run the application and test the requirements;
you will see it works as expected.
What are the Differences Between Html.CheckBox and Html.CheckBoxFor in ASP.NET Core
MVC?
The key differences between Html.CheckBox and Html.CheckBoxFor in ASP.NET Core MVC are:
Html.CheckBox: This is a weakly typed helper method. You need to specify the control’s
name as a string, and there’s no direct association with the model’s properties. For example,
@Html.CheckBox(“RememberMe”, true). Here, “RememberMe” is simply a string, and there’s
no compile-time checking for whether this name matches a model property.
Html.CheckBoxFor: This is a strongly typed helper method that binds directly to a model’s
property using a lambda expression. The advantage is that you get Visual Studio compile-time
checking and IntelliSense support. Example: @Html.CheckBoxFor(model =>
model.RememberMe). Here, model.RememberMe is tied directly to the model, and you are less
likely to make mistakes because of the strong typing.
Model Binding:
Html.CheckBox: Since it is weakly typed, IntelliSense won’t help much with suggesting model
property names or ensuring that you are typing them correctly.
Html.CheckBoxFor: IntelliSense works very well because it’s strongly typed and tied to the
model’s properties. This makes it easier to avoid mistakes when writing code.
Usage Scenario:
Html.CheckBox: Typically used when the checkbox does not need to be tied to a model’s
property (e.g., for static forms or when you manually handle the binding).
Html.CheckBoxFor: Preferred when working with strongly typed views, as it automates the
model binding process and reduces the chances of errors.
In the next article, I will discuss ListBox HTML Helper in ASP.NET Core MVC application. In this
article, I explain step-by-step how to create a Check Box HTML Helper in ASP.NET Core MVC
44
Application with examples. I hope you enjoy this Check Box HTML Helper in ASP.NET Core MVC
article.
In this article, I will discuss How to Generate a ListBox using ListBox HTML Helper in ASP.NET
Core MVC Application with Examples. Please read our previous article discussing How to Generate
Check Boxes using CheckBox HTML Helper in ASP.NET Core MVC.
Advertisements
What is a ListBox in Web Application?
A ListBox in web applications is an input element that allows users to select one or more items from a
list displayed within a box. Users interact with a ListBox by clicking on the items it contains, which can
be plain text or more complex elements depending on the application’s requirements.
Multiple Selections: A ListBox can be configured to allow users to select multiple items. This
is typically achieved by holding down the Ctrl key while clicking to select or deselect individual
items or using the Shift key to select a range of contiguous items.
Scrollable: If the number of items exceeds the space available to display them, the ListBox
can become scrollable, allowing users to navigate the list without changing its overall size.
Single-Select and Multi-Select Modes: A ListBox can operate in single-select mode, where
users can select only one item at a time, or multi-select mode, where users can select multiple
items simultaneously (usually by holding down the Ctrl key or Shift key).
HTML Structure: In HTML, a ListBox is created using the <select> element. Inside the
<select> element, you can include one or more <option> elements, each representing an
item in the list.
Labeling and Values: Each <option> element can display text and a corresponding value.
The value is sent to the server when the form is submitted.
Example of a Single Select ListBox in HTML:
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
</select>
Example of a Multi-Select ListBox in HTML:
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
In the Multi Select ListBox example, the multiple attribute on the <select> element enables users to
select multiple elements at once.
45
How Do We Create a ListBox Using HTML Helper in ASP.NET Core MVC?
To create a ListBox using HTML Helpers in ASP.NET Core MVC, we need to use Html.ListBox or
Html.ListBoxFor methods within our Razor views. The Html.ListBox method is used when you want to
specify the name of the form field manually, while Html.ListBoxFor is used with model properties,
providing a strongly typed approach. That means the ListBox() HTML Helper method is loosely typed,
whereas the ListBoxFor() HTML Helper method is strongly typed.
The ListBoxFor HTML helper in ASP.NET Core MVC is a server-side helper used to generate a <select>
HTML element with the “multiple” attribute, allowing users to select multiple options from a list. The
ListBoxFor helper is specifically designed to work with model properties. It is strongly typed, meaning
it binds directly to model properties in your MVC application, ensuring compile-time checking of the
property names you are binding to, which reduces the risk of errors.
Advertisements
Syntax: ListBoxFor<TResult>(Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList, object htmlAttributes)
Explanation of Parameters:
expression: This parameter is a lambda expression that specifies the property in the model that will
hold the selected values from the ListBox. It is strongly typed, which is tied to a specific model
property. This allows the ListBoxFor helper to bind the selected values to this model property
automatically.
selectList: This parameter provides the list of items rendered as options within the ListBox. Each item
in this list is an instance of SelectListItem, which has the following properties:
Advertisements
ListBoxFor HTML Helper Example in ASP.NET Core MVC:
Let us understand the ListBoxFor HTML helper method with an example. We need to generate the
following list box, which allows the user to select multiple options.
46
We want the user to select one or more cities from the ListBox. Once the user selects the cities and
clicks on the Submit button, we need to display the names of the selected cities separated by a
comma. If the user doesn’t select any city and clicks on the Submit button, then the No Cities are
Selected message should be displayed.
Creating Models:
First, we need to create a model that contains the list of items to be displayed in the ListBox and a
property to hold the selected item(s). So, create a class file named City.cs within the Models folder
and copy and paste the following code. The following model has three properties: CityId, CityName,
and IsSelected.
Advertisements
namespace HTML_HELPER.Models
}
Next, we need to create a View Model for use within the View. To do so, right-click on the Models folder
and add a new class file named CitiesViewModel. Once you create the CitiesViewModel, copy and
paste the following code. This class has two properties: SelectedCities and Cities.
namespace HTML_HELPER.Models
// This will hold a collection of 'City' objects, representing the list of cities available for selection in the
view.
}
Modifying Home Controller:
Next, please modify the HomeController as follows. The following code is self-explained, so please
read the comment lines for a better understanding:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
47
using System.Text;
namespace HTML_HELPER.Controllers
// Returns a list of City objects, each with a CityId, CityName, and IsSelected property
// Sample cities with their respective CityId, CityName, and a boolean IsSelected
};
// This action method handles HTTP GET requests to the Index page
[HttpGet]
// Populates the Cities property of the ViewModel with the available cities from GetAvailableCities
Cities = GetAvailableCities(),
// Sets the SelectedCityIds property by selecting the CityIds of the cities that are preselected
(IsSelected = true)
SelectedCityIds = GetAvailableCities()
};
return View(citiesViewModel);
48
// This action method handles HTTP POST requests when a form is submitted with selected cities
[HttpPost]
if (SelectedCityIds == null)
else
// First, fetch the names of the cities that were selected using the CityId
selected list
// Use StringBuilder to efficiently concatenate the city names into a single string
return sb.ToString();
}
Modify the Index View:
Next, modify the Index.cshtml view file as follows. The following code is self-explained, so please
read the comment lines for a better understanding:
@model HTML_HELPER.Models.CitiesViewModel
@{
ViewBag.Title = "Index";
<div>
@* The 'asp-action' attribute sets the action method that will handle the form submission
('SubmittedCities').
The 'asp-controller' attribute specifies the controller ('Home') that contains this action.
49
The 'method="post"' defines that this form will submit data using the HTTP POST method. *@
<div class="form-group">
The ListBoxFor binds the selected values to the 'SelectedCityIds' property in the model (m =>
m.SelectedCityIds).
The 'MultiSelectList' takes the 'Cities' collection from the model, with 'CityId' as the value field and
Additional HTML attributes, like 'class' for Bootstrap styling ('form-control') and 'size' (showing 7
</div>
@* A submit button that sends the form data to the 'SubmittedCities' action in the 'Home' controller
when clicked. *@
</form>
</div>
Note: To select multiple items from the list box, hold down the CTRL Key. Run the application and see
if everything is working as expected.
To use the ListBox HTML Helper, we need to specify the name of the form field and a list of items for
the List Box. Optionally, you can also include HTML attributes to customize the appearance or behavior
of the list box.
Parameters:
expression: This parameter represents the name of the form field that will be used when the
form is submitted.
selectList: This is a collection of SelectListItem objects, each representing one selectable
option within the <select> element. Each SelectListItem can have properties like Value, Text,
and Selected:
1. Value: The value that will be submitted if this option is selected.
2. Text: The display text in the dropdown for the user.
3.Selected: A boolean indicating whether this item should be pre-selected when the
view is rendered.
htmlAttributes: This parameter allows additional HTML attributes to be specified for the
<select> element. These attributes can be provided as an anonymous object or a dictionary.
For example, passing new { @class = “form-control”, size = 10 } would add a CSS class of
form-control and set the size attribute of the select element to 10.
Advertisements
Example using ListBox HTML Helper in ASP.NET Core MVC:
Let us understand How we can use the ListBox HTML Helper in ASP.NET Core MVC Application, which is
not a strongly typed HTML helper. We are going to do the same example using ListBox HTML Helper.
So, modify the Home Controller class as follows.
50
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Controllers
// Returns a list of City objects, each with a CityId, CityName, and IsSelected property
};
// This action method handles HTTP GET requests to the Index page
[HttpGet]
Value = city.CityId.ToString(), // CityId will be used as the value of each ListBox item
}).ToList();
ViewBag.Cities = cities;
return View();
// This action method handles HTTP POST requests when a form is submitted with selected cities
[HttpPost]
51
public string SubmittedCities(IEnumerable<int> SelectedCityIds)
if (SelectedCityIds == null)
else
// Fetch the names of the cities that were selected using the CityId
selected list
// Use StringBuilder to efficiently concatenate the city names into a single string
return sb.ToString();
}
Next, modify the Index.cshtml file as follows:
@{
ViewBag.Title = "Index";
<div>
<div class="form-group">
"form-control", size = 7 })
@* The first argument is the name ("SelectedCityIds") used for binding selected values in the POST
action.
The second argument is the IEnumerable<SelectListItem> (cast from ViewBag.Cities) that provides
52
Additional HTML attributes, like 'class' for Bootstrap styling ('form-control') and 'size' (showing 7 items
</div>
</form>
</div>
With the above changes in place, run the application, and you should get the expected output.
Let us understand this with an example. Imagine you are building an administration panel for a
company where an admin needs to assign multiple roles (e.g., Admin, Editor, Viewer) to users. The
roles are predefined and stored in the system. The admin can select multiple roles for a user from a
ListBox, which will be assigned to the user. Let us proceed and implement this example step by step:
The model contains a list of roles available in the system and a list of selected role IDs for the user. So,
create a class file named UserRoleViewModel.cs within the Models folder and then copy and paste the
following code:
namespace HTML_HELPER.Models
}
Creating Admin Controller:
The controller will fetch the available roles, assign roles to a user, and handle the form submission. So,
create an Empty MVC Controller named AdminController within the Controllers folder and then copy
and paste the following code:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
53
// This simulates fetching roles from a data source (e.g., database)
};
UserId = userId,
AvailableRoles = GetAvailableRoles()
};
return View(model);
[HttpPost]
model.AvailableRoles = GetAvailableRoles();
.ToList();
=> r.RoleName))}";
else
return View(model);
54
}
}
Creating AssignRoles View
In the view, the ListBoxFor helper method displays the list of available roles the admin can select for
the user. So, create a view named AssignRoles and then copy and paste the following code:
@model HTML_HELPER.Models.UserRoleViewModel
@{
ViewData["Title"] = "AssignRoles";
@* This creates a form element that will post data to the "AssignRoles" action of the "Admin"
controller.
The method="post" specifies that the form data will be sent using an HTTP POST request, which is
<div class="form-group">
@*
This helper creates a ListBox (multi-select list) for the property 'SelectedRoleIds' in the model.
'm => m.SelectedRoleIds' binds the ListBox to the 'SelectedRoleIds' property in the ViewModel.
'RoleId' is used as the value for each option, and 'RoleName' is used as the displayed text.
'new { @class = "form-control" }' applies the 'form-control' CSS class to the ListBox, ensuring it uses
Bootstrap styling. *@
</div>
</form>
@* This checks if there is any message stored in the ViewBag "Message" property.
@ViewBag.Message
</div>
}
Running the Application
When the admin navigates to the Admin/AssignRoles URL, they will see a list of available roles in a
multiple-select list, as shown in the image below.
55
The admin can select one or more roles and click the “Assign Roles” button, as shown in the image
below.
After submitting, the roles will be assigned to the user, and the assigned roles will be displayed in a
confirmation message, as shown in the image below.
What are the Differences Between ListBox and ListBoxFor in ASP.NET Core MVC?
56
In ASP.NET Core MVC, ListBox and ListBoxFor are helper methods for rendering HTML <select>
elements with multiple selection capabilities. However, they differ in how they bind to model data and
how they are used within views. The following are the differences:
Binding to Model:
ListBox: It does not automatically bind to a model property. You need to manually specify the
name of the select element and pass the list of items you want to display. It is useful when we
do not want to bind the selection directly to a model property.
ListBoxFor: It binds directly to a model property. This helper method is strongly typed and
takes an expression to identify the model property to which the ListBox will bind. When the
form is submitted, the selected values are automatically bound to the model property.
Strongly Typed vs. Non-Strongly Typed:
ListBox: Non-strongly typed helper method. It is not tied to a specific model property, so it is
more flexible but requires more manual handling.
ListBoxFor: Strongly typed helper method. Ensures that the ListBox is tied to a specific model
property, reducing the chances of errors and making the code more maintainable.
Use Cases:
ListBox: Suitable when you want to generate a list of selectable items without binding them to
a model or when you need more control over how the data is handled.
ListBoxFor: Suitable when you want to bind a list of items directly to a model property,
making form processing more straightforward and streamlined.
In the next article, I will discuss the Editor HTML Helper in an ASP.NET Core MVC Application. In
this article, I explain how to Create a ListBox using the ListBox HTML Helper in an ASP.NET
Core MVC Application with Examples. I hope you enjoy this ListBox HTML Helper in an ASP.NET Core
MVC article.
In this article, I will discuss How to Use Editor HTML Helper in ASP.NET Core MVC Application to
generate input HTML elements. Please read our previous article, where we discussed How to
Generate a List Box using List Box HTML Helper in ASP.NET Core MVC Application.
Advertisements
Editor HTML Helper in ASP.NET Core MVC
As of now, we have seen and used different types of HTML Helper methods to generate different types
of HTML elements in ASP.NET Core MVC applications. In ASP.NET Core MVC, the Editor helper method
generates HTML input elements based on the data type of the model property to which it’s bound. It
automatically selects the appropriate input type based on the model property’s data annotations and
type. This flexibility makes it very useful for creating form elements dynamically, especially in
scenarios where the form is generated based on the model properties.
In ASP.NET Core MVC, the Editor helper method dynamically chooses the appropriate HTML element
based on the data type of the model property it’s bound to. This decision-making is facilitated by
editor templates and the data annotations that might be applied to your model properties. The
following diagram lists the HTML element created for each data type by the Editor() or EditorFor()
method.
Advertisements
57
Example to Understand Editor HTML Helper Method in ASP.NET Core MVC:
Editor is a generic method that creates an input element for the specified model property. The Editor
HTML Helper method requires a string expression as a parameter to specify the property
name. Syntax: @Html.Editor(“PropertyName”)
Advertisements
Let’s understand how to use Editor HTML Helper in an ASP.NET Core MVC Application with one
example. First, create a class file named Employee.cs within the Models folder and copy and paste
the following code.
namespace HTML_HELPER.Models
Male,
Female,
58
Other
}
Modifying the Home Controller:
Next, create an Empty MVC Controller named EmployeeController within the Controllers folder and
copy and paste the following code.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
[HttpGet]
Age = 35,
Salary = 55000.00m,
IsEmployed = true,
Gender = Gender.Male,
ProfilePicture = null,
UserId = Guid.NewGuid(),
};
return View(model);
[HttpPost]
if (ModelState.IsValid)
return RedirectToAction("Success");
return View(model);
59
}
}
Creating the Create.cshtml View:
Next, create the Create.cshtml view and copy and paste the following code.
@model Employee
@{
ViewData["Title"] = "Create";
data">
<div class="col-md-3">
</div>
<div class="col-md-9">
your name" } })
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
age" } })
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
your salary" } })
60
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
61
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
</form>
Now, run the application; it will give you the following output. In the above example, we have specified
the property names of the Employee model. So, the Editor HTML Helper method creates the
appropriate input elements based on the datatype of Employee model properties, as shown in the
image below.
Advertisements
62
Gender Enum Not Showing All Options
The EditorFor method doesn’t automatically render a dropdown list with all enum options. To resolve
this without using DropDownListFor, we need to ensure that the editor template for the enum type is
correctly applied.
When using EditorFor with an IEnumerable<string>, the default behavior is to render one input field
for each element in the collection. To ensure a single textarea is rendered without using TextAreaFor,
we can provide a custom editor template.
Advertisements
What are Custom Editor Templates in ASP.NET Core MVC?
Custom Editor Templates in ASP.NET Core MVC are reusable Razor views that render model properties
in a custom way. Instead of rendering a form field in the default manner (e.g., a text box for strings, a
checkbox for booleans, etc.), you can create custom templates to control how specific data types or
properties are displayed.
63
These templates are stored in special folders (Views/Shared/EditorTemplates/) and are automatically
used by the EditorFor HTML helper method when rendering the corresponding model properties.
Create a custom editor template for enum types. The location will
be Views/Shared/EditorTemplates/Gender.cshtml. Once you create the Gender.cshtml view, copy
and paste the following code:
@model Enum
Create a custom editor template for IEnumerable<string> to render a single textarea. The File location
will be: Views/Shared/EditorTemplates/Skills.cshtml. Once you create the Skills.cshtml view, copy
and paste the following code. This custom editor template will render a textarea where the skills will
be displayed as a comma-separated string. You can split the string into a list of hobbies when you
submit the form.
@model List<string>
Advertisements
What is UIHint Attribute in ASP.NET Core MVC?
The UIHint attribute in ASP.NET Core MVC is used to specify which custom template should be used to
render a model property in a view. It provides a way to override the default behavior of HTML helpers
such as EditorFor, DisplayFor, or LabelFor. It instructs the framework to use a particular editor or
display template based on the attribute’s value. So, modify the Employee.cs class file as follows:
using System.ComponentModel.DataAnnotations;
namespace HTML_HELPER.Models
[UIHint("Skills")]
64
public enum Gender
Male,
Female,
Other
}
With the above changes in place, it should display the Skills separated by a comma, as shown in the
below image:
EditorFor is a strongly typed method that generates an input element based on the type of the model
property. Syntax: @Html.EditorFor(model => model.PropertyName)
The EditorFor HTML Helper method is strongly typed. As it is a strongly typed method, we must use a
lambda expression to specify the name. Let us understand this with an example. Please modify
the Index.cshtml view as shown below to use the EditorFor extension method
@model Employee
65
@{
ViewData["Title"] = "Create";
data">
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
})
</div>
</div>
66
<div class="row mb-3">
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
67
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
</div>
</div>
</form>
In the above example, we specified the property name using the lambda expression. The result is the
same whether you use the Editor() or the EditorFor() extension method. Now, run the application; it
will give you the same output.
What are the Differences Between Editor and EditorFor in ASP.NET Core MVC?
In ASP.NET Core MVC, Editor and EditorFor HTML helper methods render form fields for model
properties in a Razor view. However, they differ in how they are used and the level of control they
provide.
68
Detailed Comparison
EditorFor: This is a strongly typed helper. It uses lambda expressions to refer to the model’s
properties, providing compile-time type checking and IntelliSense support. If you rename a
property, refactoring tools can automatically update the lambda expressions in your views.
Editor: This is a non-strongly typed helper. It takes the property name as a string, meaning
there is no compile-time checking. This can lead to errors if the property name is mistyped or
renamed, as the compiler cannot verify it.
Compile-Time Checking
EditorFor: Slightly more performant because it uses strong typing and expressions.
Editor: Slightly less performant because it involves string lookup and reflection.
When to Use Editor vs EditorFor
Use EditorFor when: You have a strongly typed model, and you want the benefits of
compile-time checking, better performance, and support for refactoring tools. This is the
default and preferred approach in most ASP.NET Core MVC applications.
Use Editor when: You need to dynamically generate form fields where the property names
are not known until runtime or where you’re dealing with scenarios that do not support strong
typing (e.g., handling form fields dynamically based on user input).
In the next article, I will discuss the Password Field HTML Helper in the ASP.NET Core
MVC application and explain how to Use the Editor HTML Helper with Examples. I hope this article will
help you with your needs.
In this article, I will discuss How to Use Password Field HTML Helper in ASP.NET Core
MVC Application to Generate Password Fields with Examples. Please read our previous article
discussing How to Use Editor HTML Helper in ASP.NET Core MVC Application.
Advertisements
What is Password Input Filed in Web Application?
A password input field in a web application is a form field specifically designed for users to input their
passwords securely. In HTML, the input element with the type attribute set to “password” is used to
create a password input field. When users type their passwords into this field, the characters are
usually masked (often displayed as asterisks or dots) to prevent anyone nearby from seeing the
password. This helps protect the confidentiality of the user’s login credentials.
This input field type is designed for users to securely enter sensitive information, such as Passwords,
OTPs, PIN Codes, or other confidential data. The following is the basic structure of a password input
field in HTML:
69
How Do We Create Password Filed Using HTML Helper in ASP.NET Core MVC?
To create a Password Input Field, i.e., <input type=”password”> using HTML Helpers in ASP.NET
Core MVC, we need to use Password or PasswordFor methods within our Razor views. The Password or
PasswordFor HTML helpers render an HTML input element for the type of password. These helper
methods are helpful when we need to create a password field in a form, ensuring that the user’s input
is masked for privacy.
The Password method is used when we manually specify the form field’s name, while PasswordFor is
used with model properties, providing a strongly typed approach. That means the Password() HTML
Helper method is loosely typed, whereas the PasswordFor() HTML Helper method is strongly typed.
Advertisements
What is the Password HTML Helper Method in ASP.NET Core MVC?
The Html.Password() HTML Helper method in ASP.NET Core MVC generates an input password element
with a specified name, value, and HTML attributes. Two overloaded Password() Helper Method versions
are available.
Let’s see an example of understanding the Password HTML Helper in ASP.NET Core MVC. First, create a
class file named LoginModel.cs within the Models folder and copy and paste the following code into
it. As you can see, the following class has two properties: UserName and Password.
namespace HTML_HELPER.Models
}
Modifying Account Controller:
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
[HttpGet]
return View();
[HttpPost]
if (ModelState.IsValid)
70
{
return View(model);
}
Modifying the Login View:
@{
ViewData["Title"] = "Login";
<h2>Login Page</h2>
UserName" })
</div>
@Html.Label("Password", "Password")
Password" })
</div>
</div>
</form>
Now, run the application and access the Account/Login URL, which will open the below page:
71
Advertisements
Now, please enter some text into the Password, and you will see that it is coming as a dot, as shown in
the image below.
The PasswordFor() HTML helper method is the strongly typed extension method. Let us understand
this with an example. Please modify the Login.cshtml view as shown below.
@model LoginModel
@{
ViewData["Title"] = "Login";
<h2>Login Page</h2>
UserName" })
</div>
72
@Html.LabelFor(m => m.Password)
Password" })
</div>
</div>
</form>
In the above example, the first parameter of the PasswordFor() helper method is a lambda expression
that specifies the model property to be bound with the password field textbox. The second parameter
is an anonymous object, for which we have specified additional HTML attributes. Now, run the
application, and it should work as expected.
When Should We Use Password HTML Helper Method in ASP.NET Core MVC?
Password input fields are commonly used when you want users to securely enter passwords or other
sensitive information, such as PIN codes or confidential data. The following are some of the Real-time
scenarios where we should consider using the Password HTML Helper method:
Advertisements
User Registration and Authentication: When users register for an account or log in, you
typically use password input fields to collect their passwords securely. The password input field
helps ensure that passwords are not easily readable while being entered.
Change Password Forms: If your application has a feature that allows users to change their
passwords, you should use the Password HTML Helper to create the new password input field.
Secure Data Collection: Whenever you need users to input sensitive information, such as
credit card details, PIN codes, or confidential data, you should use the Password HTML Helper
to create the input field. This ensures the input is hidden and masked to prevent unauthorized
users from viewing it.
Password Reset Forms: When implementing a “Forgot Password” functionality, the
Password HTML Helper creates the input field where users enter their new passwords.
What are the Differences Between Password and PasswordFor in ASP.NET Core MVC?
In ASP.NET Core MVC, both Password and PasswordFor are used to generate a password input field,
but they differ in their usage and functionality. The following are the key differences between
Password and PasswordFor:
Password: This helper method generates a password input field without binding it directly to
a model property. You need to specify the name of the input field manually. It requires you to
explicitly manage the field’s name and value, making it more suitable when you don’t need
strong model binding. Example: @Html.Password(“Password”, null, new { @class =
“form-control” })
PasswordFor: This helper method is strongly typed and directly binds the password input
field to a model’s property. It automatically associates the input field with the model property
and applies validation rules specified in the model. It is the preferred option when using model
binding in strongly-typed views. Example: @Html.PasswordFor(m => m.Password, new
{ @class = “form-control” })
Advertisements
Strongly-Typed vs Weakly-Typed
Password: It is weakly typed and is not tied to any specific model property. You must pass the
field name as a string, which can be error-prone (typos, field name changes).
PasswordFor: It is strongly typed, meaning it is directly tied to a model property using
lambda expressions. This helps with compile-time checking and ensures correctness.
Usage
Password: Used in scenarios where you don’t have a strongly typed view or when you need to
dynamically generate form fields that are not directly tied to the model.
73
PasswordFor: Used in strongly typed views where the form fields are directly tied to model
properties. It’s more efficient for handling form data and validation in such contexts.
In the next article, I will discuss the Hidden Field HTML Helper in the ASP.NET Core
MVC Application and explain the Password Field HTML Helper with Examples. I hope this article
will help you with your needs.
In this article, I will discuss Hidden Field HTML Helper in ASP.NET Core MVC Application with
Examples. Please read our previous article discussing Password Field HTML Helper in ASP.NET
Core MVC Application.
A hidden input field in a web application is an HTML <input> element that is not visible to the user. It
stores data that can be sent with a form to the server upon submission. Although the user cannot see
or interact with a hidden input field, it can hold values we want to pass to the server without needing
user interaction or display. The basic syntax for a hidden input field looks like this: <input
type=”hidden” name=”hiddenFieldName” value=”someValue”>
Here, type=”hidden” specifies that the input field is hidden from the user. The name attribute
identifies the input field, and the value attribute contains the data sent to the server when the form is
submitted.
Advertisements
Note: While hidden input fields are not directly visible or editable by the user through the interface,
they can still be viewed and modified by users who inspect the page’s HTML source code or use
browser developer tools. Therefore, sensitive information should not be stored in hidden input fields
and should be properly encrypted or handled securely to prevent security vulnerabilities.
How Do We Create Hidden Filed Using HTML Helper in ASP.NET Core MVC?
To create a Hidden Field, i.e., <input type=”Hidden”> using HTML Helpers in ASP.NET Core MVC,
we must use Hidden or HiddenFor methods within our Razor views. The Hidden method is used when
you manually specify the form field’s name, while HiddenFor is used with model properties, providing a
strongly typed approach. That means the Hidden() HTML Helper method is loosely typed, whereas the
HiddenFor() HTML Helper method is strongly typed.
Advertisements
Example to Understand Hidden HTML Helper Method in ASP.NET Core MVC:
In ASP.NET Core MVC, the Hidden HTML helper generates a hidden form field. This method is useful
when we need to include data in the form submission that is not directly related to model properties or
when we want to specify the field’s name and value explicitly. The syntax
is @Html.Hidden(“fieldName,“ “value”). Here, “fieldName” is the name of the hidden field, and
“value” is the value assigned to it. When the form is submitted, the value of this hidden field is sent to
the server along with the other form data.
When you load a form to edit a record, such as a product or user, we need to pass the record’s
identifier (like the Id field) back to the server when the form is submitted. The user doesn’t need to see
or edit the ID, so it’s stored in a hidden field. Let us understand this with an example. Here, we will use
the following Student model to understand the Hidden() and HiddenFor() HTML Helper methods. First,
create a class file named Student.cs within the Models folder and copy and paste the following code.
Advertisements
namespace HTML_HELPER.Models
74
public class Student
}
Creating Student Controller:
Next, create an Empty MVC Controller named StudentController within the Controllers folder and
copy and paste the following code. Here, we have created the Controller with two action methods. The
Get version will display the Edit View, which the user can use to edit the information, and when the
form is submitted, the Post action method will handle the data.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
return View(student);
[HttpPost]
}
Creating the Edit View
Next, create the Edit view and copy and paste the following code. Here, we create a hidden field ID
with the ID property of the Student model. The hidden field will store the user’s ID; when the form is
submitted, this ID value is also submitted to the server.
@model HTML_HELPER.Models.Student
@{
ViewData["Title"] = "Edit";
@Html.Hidden("Id", Model.Id)
75
<div class="form-group mt-1">
<div class="col-md-10">
Name" })
</div>
</div>
<div class="col-md-10">
Branch" })
</div>
</div>
</div>
</div>
</form>
Here, @Html.Hidden generates a hidden input field. The first parameter (“Id”) is the input element’s
name, which will be used to identify the data on the server. The second parameter (Model.Id) is the
value you want to send along with the form. Run the application, navigate to the Student/Edit URL,
and see the following output. Please note that it shows the name and branch but not the student’s ID
value.
Advertisements
If you inspect the HTML element, you will see it generates the following HTML element for the hidden
field.
76
<input data-val=”true” data-val-required=”The Id field is
required.” id=”Id” name=”Id” type=”hidden” value=”1” />
Now, when you click on the Submit button, you will see, along with the Name and Brach, it is also
sending the ID value to the server, and you will get the following output.
Advertisements
Note: Please note that hidden fields can still be manipulated by users with some technical knowledge,
so sensitive or critical information should always be validated and processed securely on the server
side.
The HiddenFor helper method in ASP.NET Core MVC is strongly typed and is used with model
properties. It generates a hidden input field for a specific property of the model bound to the view. This
approach ensures type safety and enables direct mapping between the form field and the model
property, reducing the errors due to mistyped field names.
The HiddenFor() method takes a lambda expression as an argument, which specifies the property of
the model that the hidden input element represents. Let us understand this with an example. Please
modify the Index.cshtml file as follows:
@model HTML_HELPER.Models.Student
@{
ViewData["Title"] = "Edit";
<div class="col-md-10">
Name" })
</div>
</div>
<div class="col-md-10">
Branch" })
</div>
77
</div>
</div>
</div>
</form>
Here, Html.HiddenFor(m => m.Id) generates a hidden input field based on the model’s Id property.
The lambda expression m => m.ID specifies the property for which you want to create the hidden
field. The ID value will be included in the POST data when the form is submitted. Run the application,
and you will get the same output as the previous example.
Multi-Step Forms Real-time Example using Hidden HTML Helper Method in ASP.NET Core
MVC:
We will use hidden fields to carry data from one step to another in a multi-step form. Information
collected in previous steps must be preserved for subsequent steps without being visible to the user.
We will use a simple use case of a User Registration Process where we collect user details in multiple
steps.
In step 1, collect the user’s personal details (e.g., Name and Email). So, we will create the following to
collect the user’s personal information.
In step 2, collect address details (e.g., Street, City, and Zip Code). Once the user clicks the Next button
in Step 1, we will navigate him to the following page, where he will enter the address.
78
In Step 3, we will Review the details and submit the registration. That means once the user clicks on
the Next button in Step 2, we will navigate the user to the following page, where he will verify the
details and click on the submit button.
79
Once the user clicks on the Submit button, the data should saved in the database, and the user should
receive a successful registration message as shown in the below image:
We will start by creating a model to represent the user registration details. So, create a class file
named RegistrationViewModel.cs within the Models folder and copy and paste the following code.
using System.ComponentModel.DataAnnotations;
namespace HTML_HELPER.Models
}
Step 2: Create the Controller
80
We will manage the flow between the steps in the controller. So, create an Empty MVC Controller
named RegistrationController within the Controllers folder and copy and paste the following code.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
// Handles GET requests for the 'PersonalInfo' action, displaying the Personal Info form
[HttpGet]
return View();
[HttpPost]
// Checks if the model passed from the form is valid based on DataAnnotations
if (ModelState.IsValid)
// If the data is valid, redirect to the 'AddressInfo' action, passing the personal info as route data
// If the model is invalid, re-render the 'PersonalInfo' view with the existing model (to show validation
errors)
return View(model);
// Handles GET requests for the 'AddressInfo' action, displaying the Address Info form
[HttpGet]
// Creates a new AddressInfoViewModel and populates it with the personal info passed from the
previous step
LastName = lastName,
Email = email
};
81
// Passes the populated model to the 'AddressInfo' view
return View(model);
[HttpPost]
// Checks if the model passed from the form is valid based on DataAnnotations
if (ModelState.IsValid)
// If the data is valid, redirect to the 'RegistrationSummary' action, passing both personal and address
model.FirstName,
model.LastName,
model.Email,
model.Street,
model.City,
model.ZipCode
});
// If the model is invalid, re-render the 'AddressInfo' view with the existing model (to show validation
errors)
return View(model);
// Handles GET requests for the 'RegistrationSummary' action, displaying a summary of all the
registration details
[HttpGet]
// Creates a new RegistrationSummaryViewModel and populates it with the personal and address info
LastName = lastName,
Email = email,
City = city,
82
ZipCode = zipCode
};
return View(model);
[HttpPost]
return RedirectToAction("Success");
// Handles GET requests for the 'Success' action, displaying a success message after registration is
complete
return View();
}
The above example implements a multi-step form submission process to persist data across multiple
HTTP requests. Each registration process step has its own view and handles validation to ensure data
is correctly passed between steps. The final step involves saving the data and showing a success
message.
This is the view where the user enters their personal details. So, create a view
named PersonalInfo.cshtml and copy and paste the following code.
@model PersonalInfoViewModel
@{
ViewData["Title"] = "Step1";
83
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
</div>
</div>
</div>
</form>
Step 2 View: AddressInfo.cshtml
This view collects the user’s address details and includes hidden fields to retain the data from Step 1.
So, create a view named AddressInfo.cshtml and copy and paste the following code.
@model AddressInfoViewModel
@{
ViewData["Title"] = "Step2";
</div>
84
@Html.TextBoxFor(m => m.City, new { @class = "form-control" })
</div>
</div>
</form>
Step 3 View: RegistrationSummary.cshtml
This step reviews the data and allows the user to submit the registration, with hidden fields carrying
the data from previous steps. So, create a view named RegistrationSummary.cshtml and copy and
paste the following code.
@model RegistrationSummaryViewModel
@{
ViewData["Title"] = "Step3";
<div class="container">
<div class="card-body">
<div class="col-sm-9">@Model.FirstName</div>
</div>
<div class="col-sm-9">@Model.LastName</div>
85
</div>
<div class="col-sm-9">@Model.Email</div>
</div>
<div class="col-sm-9">@Model.Street</div>
</div>
<div class="col-sm-9">@Model.City</div>
</div>
<div class="col-sm-9">@Model.ZipCode</div>
</div>
</div>
</div>
<div class="text-center">
</div>
</form>
</div>
Success View: Success.cshtml
After submitting the form, the user is directed to the success page. So, create a view
named Success.cshtml within the Views/Shared folder and then copy and paste the following code.
@{
ViewData["Title"] = "Success";
</div>
Now, run the application and test the functionalities, and it should work as expected.
In the next article, I will discuss how to create a custom HTML helper in the ASP.NET Core
MVC application with examples and explain the hidden field of HTML helper in this article. I hope
this article will help you with your needs.
86
Custom HTML Helper in the ASP.NET Core MVC
In this article, I will discuss How We Create Custom HTML Helpers in ASP.NET Core
MVC Applications with Examples. Please read our previous article discussing Hidden Field HTML
Helper in ASP.NET Core MVC. As part of this article, we will discuss the following two important
pointers.
Advertisements
1. How can we Display Images in an ASP.NET Core MVC Application?
2. How do we Create Custom HTML Helpers in ASP.NET Core MVC to Display Images?
The ASP.NET Core MVC Framework provides many built-in HTML helper methods that we can directly
use in a Razor View. It also allows the creation of a Custom HTML Helper Method. Once you create the
custom HTML helper method, you can reuse it many times in your application.
To create a custom HTML Helper in ASP.NET Core MVC, we need to understand that HTML Helpers
generate HTML markup programmatically within Razor views. Custom HTML Helpers allow us to
encapsulate reusable pieces of HTML and logic. Let’s look at an example to understand how to Create
a Custom HTML helper in an ASP.NET Core MVC Application. We will create one page to display the
employee details, as shown in the image below. As you can see, along with the Employee ID, Name,
Designation, and Department, we also display the Employee Photo.
First, create a class file named Employee.cs within the Models Folder and copy and paste the
following code. Here, we have created the Employee model to hold the required data.
87
namespace HTML_HELPER.Models
}
Creating Images Folder within the wwwroot Folder:
Next, add a folder with the Name Images within the wwwroot Folder where we will store the
Employee photos. To do so, Right-click on the wwwroot, select Add Folder, and then rename the folder
as Images. Then download and add the following image to the Images Folder. Rename the image
name as MyPhoto.png.
Advertisements
Next, modify the Home Controller as follows. Here, we have created one action method. We initialize
the Employee object with some hardcoded data within the action method. We also set the Photo
properties to the Path of the Photo, i.e., /Images/MyPhoto.png.
Advertisements
88
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
//In Realtime you will get the data from any data source
Id = 106724,
Designation = "Manager",
Department = "IT",
Photo = "/Images/MyPhoto.png",
};
return View(employee);
}
Modifying Index.cshtml View of Home Controller:
Next, open the Index.cshtml view file and then copy and paste the following code into it.
@model HTML_HELPER.Models.Employee
@{
<div class="col-lg-6">
</div>
<div class="card-body">
<div class="col-8">
89
<p class="form-control-plaintext mb-0">@Html.DisplayFor(model => model.Id)</p>
</div>
</div>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Designation:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Department:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Photo:</strong></label>
<div class="col-8">
</div>
</div>
<div class="col-8">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Now, Run the application and navigate to the URL Home/Index. It will produce the following output.
Notice that the Photo and AlternateText property values are displayed instead of rendering the photo.
90
To display the Image, modify the Index.cshtml file as follows:
@model HTML_HELPER.Models.Employee
@{
<div class="col-lg-6">
</div>
<div class="card-body">
<div class="col-8">
</div>
</div>
91
<div class="row mb-3">
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Designation:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Department:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Photo:</strong></label>
<div class="col-8">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Notice that here we are using img HTML tag. Now, run the application and notice that the image is
displayed as expected, as shown below.
92
Advertisements
We use the code below to render Images in the ASP.NET MVC application. We are building the image
tag by passing the values for the src and alt attributes.
Though the above code is not very complex, moving this logic into its own helper method still makes
sense. We don’t want any complicated logic in our views; views should be as simple as possible. Don’t
you think it would be very nice if we could render the image using the Image() HTML helper method,
as shown below?
But, ASP.NET Core MVC does not provide any built-in Image() HTML helper. So, let’s build our own
custom image HTML helper method.
To create a custom HTML helper in ASP.NET Core MVC, we need to follow the below steps:
Create a Helper Class: Create a static class containing the custom HTML helper methods.
93
Create Extension Methods: Define extension methods within the helper class. The method
should extend the IHtmlHelper interface or any derived interface. That means the first
parameter must be this IHtmlHelper.
Implement Helper Methods: Write the logic for the custom HTML helper method within the
extension method. The extension method should generate HTML markup based on the
provided parameters.
Creating Custom Image Tag Helper:
Let us proceed and understand How We Can Create a Custom Image HTML Helper Method in ASP.NET
Core MVC. So, create a static class to hold our custom HTML Helper. This helper will generate an image
tag by accepting parameters for the src, alt, and additional HTML attributes (like class and style).
Create a class file with the name CustomHTMLHelper.cs (you can give any name) within the Models
folder (You can create it inside any folder or directory) and then copy and paste the following code into
it. The following code is self-explained, so please read the comment lines for a better understanding.
Advertisements
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace HTML_HELPER.Models
// Static classes cannot be instantiated and are typically used for utility or helper methods.
public static IHtmlContent Image(this IHtmlHelper htmlHelper, string src, string alt, object?
htmlAttributes = null)
// Creates a new <img> tag using the TagBuilder class, which helps in generating well-formed HTML
tags.
// Adds the 'src' attribute to the <img> tag with the value passed in the 'src' parameter.
imgTag.Attributes.Add("src", src);
// Adds the 'alt' attribute to the <img> tag with the value passed in the 'alt' parameter.
imgTag.Attributes.Add("alt", alt);
// Checks if there are any additional HTML attributes (such as class, style, etc.) passed in the
'htmlAttributes' parameter.
if (htmlAttributes != null)
// Converts the anonymous object 'htmlAttributes' into a dictionary of key-value pairs that represent
HTML attributes.
imgTag.MergeAttributes(attributes);
94
}
// Returns the generated <img> tag as an IHtmlContent object, which can be rendered directly in
Razor views.
return imgTag;
}
Code Explanation:
IHtmlHelper: This interface provides methods for rendering HTML elements in Razor views.
The extension method (Image) extends its functionality by adding a custom method to render
an <img> tag.
Image() Method: This is an extension method for IHtmlHelper that accepts parameters for
src, alt, and an optional htmlAttributes parameter to render an <img> tag.
TagBuilder: This class generates HTML elements programmatically. It ensures that the HTML
is well-formed and that attributes are correctly added.
AnonymousObjectToHtmlAttributes: This method converts an anonymous object (e.g.,
new { @class = “img-thumbnail” }) into a dictionary of attributes (e.g., class=”img-
thumbnail”). This makes it easy to pass HTML attributes without manually building the
dictionary.
Use the Custom HTML Helper:
Now that we have created our custom helper method, we can use it in your view. So, modify
the Index.cshtml file as shown below. In the below example, the Custom Image HTML Helper method
generates an <img> tag with the specified src, alt, and optional HTML attributes.
@model HTML_HELPER.Models.Employee
@{
<div class="col-lg-6">
</div>
<div class="card-body">
<div class="col-8">
</div>
</div>
<div class="col-8">
95
</div>
</div>
<label class="col-4"><strong>Designation:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Department:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Photo:</strong></label>
<div class="col-8">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Now, with the above changes in place, run the application, and you will get the output as expected, as
shown in the image below.
96
So, Custom HTML Helpers provide a convenient way to encapsulate complex HTML generation logic,
making views cleaner and more maintainable. They can be especially useful when generating custom
HTML elements that require specific attributes or behaviors.
Now, instead of creating the Image method as an extension method, we can also create this as a non-
extension method and use it inside our views. For example, modify the CustomHTMLHelper class as
follows:
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace HTML_HELPER.Models
// Static classes are typically used for helper methods and cannot be instantiated.
97
// Defines a static method named Image that returns IHtmlContent (used for rendering HTML content
in Razor views).
// This method accepts 'src' (image source URL), 'alt' (alternative text), and optional HTML attributes.
public static IHtmlContent Image(string src, string alt, object? htmlAttributes = null)
// Creates a new <img> tag using the TagBuilder class, which helps in generating well-formed HTML
tags.
// Adds the 'src' attribute to the <img> tag, setting it to the value passed by the 'src' parameter.
imgTag.Attributes.Add("src", src);
// Adds the 'alt' attribute to the <img> tag, setting it to the value passed by the 'alt' parameter.
imgTag.Attributes.Add("alt", alt);
// This parameter contains additional HTML attributes such as class, style, etc.
if (htmlAttributes != null)
// These key-value pairs represent HTML attributes and their values (e.g., class, style, id).
// Merges the additional HTML attributes (if any) into the <img> tag.
// If the <img> tag already has attributes, they are preserved and not overwritten.
imgTag.MergeAttributes(attributes);
return imgTag;
}
Now, the above Image method is not an extension method, and hence, we cannot invoke it using
the @Html property. Instead, we can call it using the class name, i.e., CustomHTMLHelper. So,
modify the Index.cshtml file as follows.
@model HTML_HELPER.Models.Employee
@{
<div class="col-lg-6">
98
<h4 class="mb-0">Employee Details</h4>
</div>
<div class="card-body">
<div class="col-8">
</div>
</div>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Designation:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Department:</strong></label>
<div class="col-8">
</div>
</div>
<label class="col-4"><strong>Photo:</strong></label>
<div class="col-8">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Now, run the application, and you should get the same output.
99
Custom HTML Helpers in ASP.NET Core MVC should be used when:
Reusability of Common HTML Code: If you repeatedly write the same HTML and logic
across multiple views (e.g., rendering images, buttons, or other complex UI components),
custom HTML helpers can encapsulate that logic and HTML into a reusable method. This
ensures consistency and reduces code duplication.
Simplifying Views: Views should focus on presentation, not logic. Moving complex logic or
repetitive code into custom HTML helpers keeps the views clean and more readable.
Consistency Across Views: Custom HTML helpers ensure that certain elements (e.g.,
buttons, inputs, image tags) are rendered consistently across the application. Any changes to
the helper reflect across all views that use it, ensuring consistency in the UI.
Separation of Concerns: By moving code that isn’t purely for presentation out of views and
into helpers, you are following the separation of concerns principle. Helpers deal with HTML
generation, while views deal with the display, making both easier to maintain and test.
In the next article, I will discuss Real-Time Examples of Custom HTML Helpers in ASP.NET Core
MVC Applications. In this article, I explain how to Create a Custom Image HTML Helper in
an ASP.NET Core MVC Application with Examples. I hope this article on creating a custom image
HTML helper in ASP.NET Core MVC will help you with your needs.
I will discuss Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications
with Examples in this article. Please read our previous article discussing How to Create Custom
HTML Helpers in ASP.NET Core MVC.
Advertisements
Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC
In ASP.NET Core MVC, HTML helpers are methods you can use in Razor views to generate HTML
content. The built-in HTML helpers are provided by the HtmlHelper class. However, you can also create
custom HTML helpers by defining extension methods for the IHtmlHelper interface. Let us proceed and
try to understand a few real-time examples of using Custom HTML Helpers in ASP.NET Core MVC
Application.
Often, form controls come with validation messages, tooltips, and specific CSS styles. Instead of
repeating the same structure, a custom HTML helper can encapsulate this pattern. Example: An input
field that automatically displays validation errors next to it
Let us create a Custom HTML Helper to render an input with validation attributes. So, create a class
file with the name FormControlHelpers.cs within the Models folder and copy and paste the following
code.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HTML_HELPER.Models
100
<div class='form-group'>
<label for='{modelPropertyName}'>{labelText}</label>
asp-for='{modelPropertyName}' />
</div>";
}
Next, modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
return View();
}
Next, modify the Index.cshtml view file as follows. As you can see, we are using the
CustomInputWithValidation HTML Helper method here.
Displaying navigational breadcrumbs on a site can be streamlined using a custom helper that takes
the current path or a list of paths and then renders the breadcrumb navigation.
Generate breadcrumb navigation based on the provided list of paths. So, create a class file with the
name BreadcrumbHelpers.cs within the Models folder and copy and paste the following code.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Models
Name)> paths)
101
var stringBuilder = new StringBuilder();
stringBuilder.Append("<nav aria-label='breadcrumb'>");
stringBuilder.Append("<ol class='breadcrumb'>");
path.Name);
stringBuilder.Append("</ol></nav>");
}
Next, modify the Index.cshtml view as follows. As you can see, we are using the Breadcrumbs HTML
Helper method here.
@{
("/", "Home"),
("/products", "Products"),
};
@Html.Breadcrumbs(breadcrumbs)
Example3: SEO Meta Tag Helper
Helpers can be created to generate SEO-friendly meta tags, structured data, or other SEO-specific
elements to be added to a page dynamically.
A helper that outputs meta tags for SEO. So, create a class file with the name SeoHelpers.cs within the
Models folder and then copy and paste the following code.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HTML_HELPER.Models
102
}
Next, modify the Index.cshtml view as follows. As you can see, we are using the MetaDescription
HTML Helper method here.
When supporting multiple themes or brands, a custom helper can determine the current theme or
brand and generate the appropriate CSS links, logos, and other related assets.
Render a CSS link based on the current theme. So, create a class file with the
name ThemeHelpers.cs within the Models folder and then copy and paste the following code into it.
Advertisements
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HTML_HELPER.Models
}
Next, modify the Index.cshtml view as follows. As you can see, we are using the RenderThemeCss
HTML Helper method.
@Html.RenderThemeCss("dark-theme")
Example5: Pagination Controls
For displaying large lists, pagination is essential. A custom helper can generate a standard pagination
control based on the current page, total items, and items per page. A helper to create pagination
controls. So, create a class file named PaginationHelpers.cs within the Models folder and copy and
paste the following code.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Models
totalPages)
103
StringBuilder result = new StringBuilder();
result.Append("<nav><ul class='pagination'>");
if (i == currentPage)
else
result.Append("</ul></nav>");
}
Next, modify the Index.cshtml view as follows. As you can see here, we are using the CreatePagination
HTML Helper method.
@Html.CreatePagination(2, 10)
Example6: Dynamic Menus
Menus that change based on user roles, permissions, or other criteria can be encapsulated within a
custom HTML helper, ensuring consistent rendering across views.
Dynamic Menus using Custom HTML Helper Methods in ASP.NET Core MVC. Dynamic menus often
depend on user roles, permissions, or other dynamic criteria. You can consistently generate these
menus across views using a custom HTML helper. Here’s an example of creating and using a custom
HTML helper to generate dynamic menus in ASP.NET Core MVC.
Advertisements
Step 1: Define Your Menu Model
First, let’s create a class file with the name MenuItem.cs within the Models folder and then copy and
paste the following code into it. This is a simple model for menu items:
namespace HTML_HELPER.Models
104
}
Step 2: Create a Custom HTML Helper for the Dynamic Menu
Next, create another class file with the name MenuHtmlHelpers.cs within the Models folder and copy
and paste the following code into it. This helper will generate the necessary HTML based on a list of
MenuItem:
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Models
result.Append("<ul class='menu'>");
if (item.SubItems.Count > 0)
result.Append("<ul class='submenu'>");
result.Append("</ul>");
result.Append("</li>");
result.Append("</ul>");
}
Step 3: Use the Custom HTML Helper in a Razor View
Let’s say you’ve populated a List<MenuItem> based on some logic (e.g., user permissions). You can
then pass this list to the custom helper to generate the dynamic menu. So, modify the Index.cshtml
file as shown below.
105
Advertisements
@using HTML_HELPER.Models
@model List<MenuItem>
@Html.DynamicMenu(Model)
Step 4: Populate the List<MenuItem> Dynamically
The actual list of MenuItem objects might be generated in your controller based on user roles,
permissions, or other criteria, and here we have hard-coded the same. So, modify the Home Controller
class as follows.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
new MenuItem
Text = "Home",
Url = "/Home/Index",
IsActive = true
},
new MenuItem
Text = "Admin",
Url = "/Admin",
};
return View(menu);
}
In this example, the Index method populates the menu and passes it to the view. The view then uses
the custom HTML helper to render the dynamic menu. This approach allows you to adapt and extend
the menu generation logic to fit various scenarios and requirements.
106
Example7: Reusable Widgets
Components like sidebars, content cards, or user profile boxes that appear across various views can
be generated using custom HTML helpers. Using custom HTML helpers to create reusable widgets is a
great way to maintain a clean and organized codebase and ensure consistent rendering across views.
Here’s an example to demonstrate creating and using such reusable widgets.
Advertisements
Example: Profile Card Widget
Imagine you have a profile card that displays a user’s name, profile image, and a short bio. This card
might be reused in different parts of your website: user lists, comments section, article authors, etc.
First, let’s create a simple model for the profile card. So, create a class file with the
name ProfileCardModel.cs within the Models folder and copy and paste the following code into it.
namespace HTML_HELPER.Models
}
Define Custom HTML Helper:
Create the Custom HTML Helper for the Profile Card. So, create a class file with the
name WidgetHtmlHelpers.cs within the Models folder and copy and paste the following code into it.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Models
result.Append("<div class='profile-card'>");
model.Name);
result.AppendFormat("<h2>{0}</h2>", model.Name);
result.AppendFormat("<p>{0}</p>", model.Bio);
result.Append("</div>");
107
return new HtmlString(result.ToString());
}
Using the Custom HTML Helper
Use the Custom HTML Helper in a Razor View. So, modify the Index.cshtml file as follows. To use the
profile card widget, we can invoke the custom helper:
@using HTML_HELPER.Models
@model ProfileCardModel
@Html.ProfileCard(Model)
Modifying Home Controller:
We need to populate the ProfileCardModel from our controller and send it to the view. So, modify the
Home Controller class as follows.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
ProfileImageUrl = "/path/to/image.jpg",
};
return View(model);
}
Benefits:
Consistency: By defining the widget’s structure and styling in one place, you ensure it looks
and behaves consistently everywhere it’s used.
Easier Maintenance: Changes to the widget (e.g., adding an email field) only need to be
made in one location.
Cleaner Views: Your Razor views are tidier as they can leverage the helper instead of
repeating HTML structures.
Flexibility: By designing your widgets to accept configurations or additional parameters, you
can make them versatile to handle different scenarios or styles.
Remember, if the widget becomes too complex, or you want to utilize more MVC features, turning the
widget into a View Component might be better than using an HTML helper. View Components in
ASP.NET Core allow you to encapsulate view and logic into a reusable unit, which is perfect for
complex widgets.
108
Example8: Configurable Data Tables
A table displaying data from various sources with options for sorting, filtering, and specifying columns.
A custom helper can take in this configuration and render the table accordingly.
Creating configurable data tables using custom HTML helper methods can provide a flexible and
reusable way to display tabular data across your application. Here’s a basic example to illustrate the
process.
Firstly, define the configuration for the data table, specifying the columns you want to display and any
other properties you may need. So, create a class file with the name DataTableConfig.cs within the
Models folder and copy and paste the following code into it.
namespace HTML_HELPER.Models
}
Create another class file named MyCustomDataType.cs and copy and paste the following code into
it. This is the class that is going to hold the model data.
namespace HTML_HELPER.Models
}
Create the Custom HTML Helper for the Data Table
Next, design your custom HTML helper. So, create a class file
named DataTableHtmlHelpers.cs within the Models folder and copy and paste the following code
into it.
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
namespace HTML_HELPER.Models
109
public static HtmlString DataTable<T>(this IHtmlHelper htmlHelper, IEnumerable<T> data,
DataTableConfig config)
// Table start
// Header
result.Append("<thead><tr>");
result.AppendFormat("<th>{0}</th>", column);
result.Append("</tr></thead>");
// Body
result.Append("<tbody>");
result.Append("<tr>");
result.AppendFormat("<td>{0}</td>", value);
result.Append("</tr>");
result.Append("</tbody>");
// Table end
result.Append("</table>");
}
Use the Custom HTML Helper in a Razor View
Now, you can use the data table widget in a Razor view. So, modify the Index.cshtml file as follows.
@using HTML_HELPER.Models
@model IEnumerable<MyCustomDataType>
@{
110
};
@Html.DataTable(Model, config)
Modifying Home Controller:
From your controller, you need to populate a list of MyCustomDataType and send it to the view. So,
modify the Home Controller as follows.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
new MyCustomDataType { Name = "Pranaya", Age = 35, Address = "123 ABC St." },
new MyCustomDataType { Name = "Kumar", Age = 34, Address = "456 PQR St." },
new MyCustomDataType { Name = "Rout", Age = 33, Address = "789 XYZ St." }
};
return View(data);
}
Notes:
Flexibility: This example provides a basic structure. You can extend the DataTableConfig
class with more configuration options (e.g., specifying which columns are sortable, adding
custom classes for specific columns, etc.).
Complex Columns: This example assumes each column is tied to a direct property on the
data type. If you have more complex columns, adjustments would be needed.
Consider using View Components or integrating a dedicated front-end library for large, complex, or
highly interactive tables.
By implementing custom HTML helpers for these use cases, developers can ensure consistency,
reduce errors, and simplify the process of making global changes to the application’s views.
In the next article, I will discuss Creating Form Using HTML Helpers in ASP.NET Core
MVC Applications with an Example. I explain Real-Time Examples of Custom HTML Helpers in ASP.NET
Core MVC Applications with Examples in this article. I hope this Real-Time Examples of Custom HTML
Helpers in ASP.NET Core MVC Applications article will help you with your needs.
111
In this article, I will discuss Creating HTML Form Using HTML Helpers in ASP.NET Core MVC Applications
with an Example. Please read our previous article discussing Real-Time Examples of Custom HTML
Helpers in ASP.NET Core MVC Applications with Examples.
Advertisements
Using HTML Helpers in ASP.NET Core MVC
Creating HTML forms in ASP.NET Core MVC with HTML Helpers simplifies the process of generating
HTML elements tied to the model properties. HTML Helpers are server-side methods that return HTML
strings that are then rendered in the browser. This approach allows for clean, maintainable, and
reusable code. Here’s a step-by-step guide to creating a form using HTML Helpers in an ASP.NET Core
MVC application.
Let’s create an example that uses various HTML helpers with Bootstrap styling. We will create a form
for user registration that includes fields for Name, Email, Password, Address, Gender, RememberMe,
Courses, Skills, etc.
Advertisements
Create a Model
First, we need to define a model representing the data we want to collect from the user. Create a class
file named UserRegistrationModel.cs within the Models folder, and then copy and paste the
following code. The UserRegistrationModel class contains various properties with data annotations for
validation.
using System.ComponentModel.DataAnnotations;
namespace HTML_HELPER.Models
[DataType(DataType.Password)]
112
public List<string> Skills { get; set; }
}
Create the Controller
Create a controller with actions to display and process the form data. The controller will have three
actions: one for displaying the form (HTTP GET), another for processing the form data (HTTP POST). So,
create an Empty MVC Controller named UserController within the Controllers folder and copy and
paste the following code. The UserController manages the GET and POST actions for user registration.
Hardcoded lists are provided for courses and skills.
Advertisements
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
[HttpGet]
HiddenField = Guid.NewGuid()
};
return View(model);
[HttpPost]
if (ModelState.IsValid)
// You can save the model data to the database or process it as needed here.
return View(model);
113
}
}
Create the View:
Add a Register.cshtml view file inside the Views/User folder, and then please copy and paste the
following code. Here, we use HTML Helpers to create form fields bound to the model properties. To
make the HTML form responsive, we use Bootstrap.
@model UserRegistrationModel
@{
ViewData["Title"] = "Register";
</div>
<div class="col-md-7">
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>
114
<div class="col-md-2 d-flex align-items-center">
</div>
<div class="col-md-7">
</div>
</div>
<label class="form-label">Gender</label>
</div>
<div class="col-md-7">
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>
</div>
<div class="col-md-7">
control" })
</div>
</div>
115
</div>
</div>
</div>
</form>
</div>
HTML Helper Methods Used in the Example:
LabelFor:
This HTML Helper generates a <label> element for a specified model property. It binds the label text
to the property name, clearly indicating which input field the label is associated with.
Advertisements
Example: @Html.LabelFor(m => m.Name, new { @class = “form-label” })
Result: Generates a label for the Name property, e.g., <label for=”Name” class=”form-
label”>Name</label>.
TextBoxFor:
This helper generates a single-line <input type=”text”> element bound to a model property. It
automatically fills the text box with the current value of the property.
This helper generates an <input type=”password”> element. The value entered is masked to protect
sensitive data such as passwords.
This helper generates a <textarea> element, which is used for multi-line input. It binds to the model
property and fills it with the property’s value.
This helper generates an individual <input type=”radio”> element bound to a property. It allows users
to choose one of many predefined options.
Example:
1. @Html.RadioButtonFor(m => m.Gender, “Male”)
2.
@Html.RadioButtonFor(m => m.Gender, “Female”)
Result: Generates radio buttons for Male and Female values.
CheckBoxFor:
116
This helper generates an <input type=”checkbox”> element bound to a Boolean property. It allows
users to toggle a state (e.g., “Remember Me”).
This helper generates a <select> element, often referred to as a dropdown list. It binds to a model
property and provides a list of options the user can select.
This helper generates a multiple-selection <select> element (i.e., a list box). It binds to a model
property and allows the user to select multiple values.
This helper generates a hidden <input type=”hidden”> field. It stores data that is not visible to the
user but is included when the form is submitted.
This helper displays validation error messages for a specific model property. It renders only if
validation errors exist for that property.
Create a Success.cshtml file inside the Views/User folder and then copy and paste the following
code.
@model UserRegistrationModel
@{
ViewData["Title"] = "Success";
<ul class="list-group">
117
<li class="list-group-item"><strong>Selected Course:</strong> @Model.SelectedCourse</li>
</ul>
<hr />
</div>
</div>
How It Works
When the user navigates to the /User/Register, the Register action is triggered in the controller, and
the view Register.cshtml is returned. The HTML helpers in the view render HTML form elements,
such as text boxes, radio buttons, and dropdown lists, all bound to properties of the
UserRegistrationModel.
When the user fills in the form and clicks the “Register” button, the form data is sent to the server via
an HTTP POST request to the Register action method in the UserController. The form data is
automatically mapped to the UserRegistrationModel using model binding, and validation is performed
based on the data annotations applied to the model.
After the form submission, the user is redirected to the Success page if validation is successful, which
renders a success message. If validation fails, the form is re-rendered, and validation errors are
displayed.
Advertisements
Running the Application
When you run the application and navigate to the /User/Register URL, you will see the Registration
Page. Please fill out the form with valid data and click on the Register button, as shown in the image
below.
118
Once you click the Register button and if the provided data is valid, the user will be registered, and the
following success page will display.
119
Advertisements
In the next article, I will discuss Generating Links in ASP.NET Core MVC Applications with
Examples. In this article, I explain how to create forms using HTML helpers in ASP.NET Core
MVC applications with an example. I hope you enjoy this “Creating Forms Using HTML Helpers in
ASP.NET Core MVC” article.
In this article, I will discuss Different Ways to Generate Links in ASP.NET Core MVC
Applications with Examples. Please read our previous article discussing Creating Form Using
HTML Helpers in ASP.NET Core MVC Applications with Examples.
Advertisements
Different Ways to Generate a Link in ASP.NET Core MVC
Creating links in ASP.NET Core MVC is essential for navigating between different parts of your web
application. In ASP.NET Core MVC, links can be generated in several ways. These techniques enable
you to create URLs that can lead to different parts of your application, such as controller actions, static
files, or external websites. The following are some of the most common methods for generating links
in ASP.NET Core MVC:
Html.ActionLink
Html.RouteLink
120
Action Tag Helper
Url.Action
Url.RouteUrl
Html.ActionLink
The ActionLink is an HTML helper method used in ASP.NET Core MVC views to generate an anchor
(<a>) element that links to a specific action method on a controller. The following is the syntax:
Parameters:
This method generates a link based on routing information rather than a specific controller and action.
The following is the syntax:
Parameters:
The Action Tag Helper is a more modern approach to generating links in Razor views using Razor
syntax. This helper allows you to generate links by using controller and action names, and it helps
create a strongly typed link generation mechanism that reduces errors in manually specifying URLs.
The following is the syntax:
<a asp-controller=”ControllerName” asp-action=”ActionName” asp-route-
id=”@Model.Id”>Link Text</a>
Advertisements
Here,
This generates a URL as a string, which you can use anywhere in your views or controllers. This is
useful in scenarios where we need the URL rather than an anchor tag. The following is the syntax:
Here,
121
specify the href attribute value of an anchor tag as follows:
<a href=”@Url.Action(“ActionName”, “ControllerName”, new { id = 1 })”>Link Text</a>
Advertisements
Url.RouteUrl
This is similar to Url.Action, i.e., generates a URL string, but instead of specifying the action and
controller, we use a route name. The following is the syntax:
@Url.RouteUrl(“RouteName”, new { id = Model.Id })
Here,
Let’s assume we are working on a Product Management system with a Product Controller. The Product
Controller has two action methods: List and Details. The List method will render a view displaying all
the products Names, with each product having a link to display the product details. The Details action
method will take the Product ID and render that Product information. In this example, I will show you
how to generate the link with all the options in the List View. Clicking on the link will render the Details
view. Let us proceed and see how to implement this step by step:
Advertisements
Creating the Product Model:
First, create a class file named Product.cs within the Model folder and then copy and paste the
following code. This will be our model, which will hold the Product information.
namespace HTML_HELPER.Models
}
ProductsController
Next, create an empty MVC Controller named ProductsController and copy and paste the following
code. As discussed, the following Controller has two action methods. The List() action method
Retrieves and displays a list of products. The Details(int id) action method Retrieves and displays the
details of a specific product based on its id.
using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
122
namespace HTML_HELPER.Controllers
// Defining individual Product objects with properties such as Id, Name, Description, Category, Price,
and Quantity.
new Product { Id = 1, Name = "Laptop", Description = "A powerful laptop.", Category = "Electronics",
};
// This action method handles requests to the "List" action in the controller.
// It returns a view displaying the list of products by passing the _products list to the view.
// Return the 'List' view and pass the _products collection to it for rendering.
return View(_products);
// This action method handles requests to the "Details" action in the controller.
// It accepts an 'id' parameter that is used to identify and retrieve a specific product.
// Using the List.Find method to search the _products list for a product with the matching Id.
// Return the 'Details' view and pass the selected product to it for rendering.
return View(product);
}
Creating a Route:
Next, add the following code to the Program.cs class file. Here, we are adding a new route with the
name ProductDetails. We will use this route name inside a view to generate the link.
app.MapControllerRoute(
123
// This can be used later for URL generation.
name: "ProductDetails",
// Defining the URL pattern that will be matched for this route.
// "{id}" is a route parameter placeholder that will capture the product's ID from the URL.
pattern: "Products/Details/{id}",
// Specifying default route values that will be used if none are provided in the URL.
// Here, the controller is set to "Products" and the action method is set to "Details".
);
Creating Views
Let’s create views for these actions and demonstrate different link-generation methods.
List View
Create the List.cshtml view and copy and paste the following code. This view displays a list of
product names and uses different mechanisms to generate links. Clicking on the link will navigate to
the Product details page and display that product information:
Advertisements
@model IEnumerable<HTML_HELPER.Models.Product>
@{
<div class="table-responsive">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>ActionLink</th>
<th>RouteLink</th>
<th>Tag Helper</th>
<th>Action</th>
<th>RouteUrl</th>
</tr>
</thead>
<tbody>
<tr>
124
<td>@item.Name</td>
<td>
btn-sm" })
</td>
<td>
btn-sm" })
</td>
<td>
btn-sm">View</a>
</td>
<td>
sm">View</a>
</td>
<td>
sm">View</a>
</td>
</tr>
</tbody>
</table>
</div>
Details View
Next, create the Details.cshtml view. This view displays a product’s details. The DisplayNameFor
helper methods display the model’s property name, and the DisplayFor method displays the
associated value of the property.
@model HTML_HELPER.Models.Product
@{
<div class="card">
<div class="card-body">
<dl class="row">
<dt class="col-sm-4">ID:</dt>
<dd class="col-sm-8">
125
@Html.DisplayFor(model => model.Id)
</dd>
<dt class="col-sm-4">Name:</dt>
<dd class="col-sm-8">
</dd>
<dt class="col-sm-4">Description:</dt>
<dd class="col-sm-8">
</dd>
<dt class="col-sm-4">Category:</dt>
<dd class="col-sm-8">
</dd>
<dt class="col-sm-4">Price:</dt>
<dd class="col-sm-8">
</dd>
<dt class="col-sm-4">Quantity:</dt>
<dd class="col-sm-8">
</dd>
</dl>
</div>
</div>
</div>
</div>
Now, run the application and navigate to the Products/List URL, and you should see the following
page:
126
Now, if you click any of the links on the above page, then it should open the Details Page as shown in
the below image:
Advertisements
The following are the key differences between Html.ActionLink, Html.RouteLink, Action Tag Helper,
Url.Action, and Url.RouteUrl in ASP.NET Core MVC:
Html.ActionLink
127
Purpose: Generates an HTML <a> element that links to a specified action method on a
controller.
Routing: Relies on the default MVC routing based on controller and action names.
Usage: Typically used in Razor views when we want to generate an anchor link directly to a
controller’s action.
Return Type: Returns an anchor (<a>) tag with the URL embedded in the href attribute.
Html.RouteLink
Purpose: Generates an HTML <a> element, but based on route names rather than directly
specifying controller and action names.
Routing: Relies on custom routes defined in the Program.cs class file.
Usage: It is useful when we have custom routes and need to generate links that use those
routes rather than hardcoding controller/action names.
Return Type: Returns an anchor (<a>) tag with the URL based on the route name.
Action Tag Helper
Purpose: Generates an anchor (<a>) tag using Razor syntax and tag helpers, which are easier
to read and maintain.
Routing: Relies on the default MVC routing based on controller and action names, similar to
Html.ActionLink.
Usage: Modern, declarative approach to creating links in Razor views.
Return Type: Returns an anchor (<a>) tag with the URL embedded in the href attribute,
automatically generated using the specified controller/action.
Url.Action
Purpose: Generates a URL string (not an anchor tag) to a specific action method on a
controller.
Routing: Similar to Html.ActionLink, relies on default MVC routing.
Usage: Used when we need a URL string to be used dynamically, such as when manually
constructing HTML elements.
Return Type: Returns a URL string pointing to the specified action.
Url.RouteUrl
Purpose: Generates a URL string based on route names or custom routes rather than
specifying controller and action names.
Routing: Uses custom routes defined in the routing configuration.
Usage: Similar to Url.Action, but works with custom routing or named routes.
Return Type: Returns a URL string based on the route name.
Choosing the Right Approach:
Use Html.ActionLink: When you need simple anchor links based on action/controller.
Use Html.RouteLink: When you are working with named/custom routes and need a link.
Use Action Tag Helper: For modern, cleaner link generation in Razor pages.
Use Url.Action: When you need the URL as a string for JavaScript or other dynamic uses.
Use Url.RouteUrl: When you need the URL as a string but based on custom routes or named
routes.
In the next article, I will discuss Tag Helpers in ASP.NET Core MVC Application with Examples. In
this article, I explain Different Ways to Generate Links in ASP.NET Core MVC Applications with
Examples. I hope you enjoy this “Different Ways to Generate Links in ASP.NET Core MVC” article.
128
129