Back to: ASP.NET Core Tutorials For Beginners and Professionals
Creating HTML Form Using HTML Helpers in ASP.NET Core MVC
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.
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.
Example using HTML Helpers in ASP.NET Core MVC:
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.
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 { public class UserRegistrationModel { [Required(ErrorMessage = "Name is required")] public string Name { get; set; } [Required(ErrorMessage = "Email is required")] [EmailAddress(ErrorMessage = "Invalid Email Address")] public string Email { get; set; } [Required(ErrorMessage = "Password is required")] [DataType(DataType.Password)] public string Password { get; set; } [Required(ErrorMessage = "Address is required")] public string Address { get; set; } [Required(ErrorMessage = "Gender is required")] public string Gender { get; set; } public bool RememberMe { get; set; } [Required(ErrorMessage = "Please select a course")] public string SelectedCourse { get; set; } public List<string> Courses { get; set; } [Required(ErrorMessage = "Please select one or more skills")] public List<string> SelectedSkills { get; set; } public List<string> Skills { get; set; } public Guid HiddenField { 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.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class UserController : Controller { [HttpGet] public IActionResult Register() { var model = new UserRegistrationModel { Courses = new List<string> { "ASP.NET Core", "Azure", "Microservices" }, Skills = new List<string> { "C#", "SQL", "JavaScript", "Docker", "Kubernetes" }, HiddenField = Guid.NewGuid() }; return View(model); } [HttpPost] public IActionResult Register(UserRegistrationModel model) { if (ModelState.IsValid) { // You can save the model data to the database or process it as needed here. // Pass the model data to the Success view return View("Success", model); } // Re-populate the Courses and Skills if validation fails model.Courses = new List<string> { "ASP.NET Core", "Azure", "Microservices" }; model.Skills = new List<string> { "C#", "SQL", "JavaScript", "Docker", "Kubernetes" }; return View(model); } } }
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 class="container mt-5"> <h2 class="text-center">User Registration</h2> <form asp-action="Register" method="post" class="mt-4"> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.Name, new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.TextBoxFor(m => m.Name, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Name, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.Email, new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Email, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.Password, new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.Address, new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.TextAreaFor(m => m.Address, new { @class = "form-control", rows = 3 }) @Html.ValidationMessageFor(m => m.Address, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> <label class="form-label">Gender</label> </div> <div class="col-md-7"> @Html.RadioButtonFor(m => m.Gender, "Male") Male @Html.RadioButtonFor(m => m.Gender, "Female", new { @class = "ms-3" }) Female @Html.ValidationMessageFor(m => m.Gender, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.SelectedCourse, new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.DropDownListFor(m => m.SelectedCourse, new SelectList(Model.Courses), "Select Course", new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.SelectedCourse, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.LabelFor(m => m.SelectedSkills, "Skills", new { @class = "form-label me-2" }) </div> <div class="col-md-7"> @Html.ListBoxFor(m => m.SelectedSkills, new MultiSelectList(Model.Skills), new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.SelectedSkills, null, new { @class = "text-danger" }) </div> </div> <div class="row mb-3"> <div class="col-md-2 d-flex align-items-center"> @Html.CheckBoxFor(m => m.RememberMe, new { @class = "form-check-input me-2" }) </div> <div class="col-md-7 d-flex align-items-center"> @Html.LabelFor(m => m.RememberMe, new { @class = "form-check-label" }) </div> </div> @Html.HiddenFor(m => m.HiddenField) <button type="submit" class="btn btn-primary">Register</button> </form> </div>
HTML Helper Methods Used in the Example:
We have used the following HTML helper methods in our 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.
- 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.
- Example: @Html.TextBoxFor(m => m.Name, new { @class = “form-control” })
- Result: Generates a text input field bound to the Name property.
PasswordFor:
This helper generates an <input type=”password”> element. The value entered is masked to protect sensitive data such as passwords.
- Example: @Html.PasswordFor(m => m.Password, new { @class = “form-control” })
- Result: Generates a password input field.
TextAreaFor:
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.
- Example: @Html.TextAreaFor(m => m.Address, new { @class = “form-control”, rows = 3 })
- Result: Generates a text area bound to the Address property.
RadioButtonFor:
This helper generates an individual <input type=”radio”> element bound to a property. It allows users to choose one of many predefined options.
- Example:
-
- @Html.RadioButtonFor(m => m.Gender, “Male”)
- @Html.RadioButtonFor(m => m.Gender, “Female”)
-
- Result: Generates radio buttons for Male and Female values.
CheckBoxFor:
This helper generates an <input type=”checkbox”> element bound to a Boolean property. It allows users to toggle a state (e.g., “Remember Me”).
- Example: @Html.CheckBoxFor(m => m.RememberMe, new { @class = “form-check-input” })
- Result: Generates a checkbox bound to the RememberMe property.
DropDownListFor:
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.
- Example: @Html.DropDownListFor(m => m.SelectedCourse, new SelectList(Model.Courses), “Select Course”, new { @class = “form-control” })
- Result: Generates a dropdown list bound to the SelectedCourse property, with options hardcoded in the controller.
ListBoxFor:
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.
- Example: @Html.ListBoxFor(m => m.SelectedSkills, new MultiSelectList(Model.Skills), new { @class = “form-control” })
- Result: Generates a list box bound to the SelectedSkills property.
HiddenFor:
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.
- Example: @Html.HiddenFor(m => m.HiddenField)
- Result: Generates a hidden field bound to the HiddenField property.
ValidationMessageFor:
This helper displays validation error messages for a specific model property. It renders only if validation errors exist for that property.
- Example: @Html.ValidationMessageFor(m => m.Name, null, new { @class = “text-danger” })
- Result: Displays a validation message for the Name property in case of validation errors.
Success View:
Create a Success.cshtml file inside the Views/User folder and then copy and paste the following code.
@model UserRegistrationModel @{ ViewData["Title"] = "Success"; } <div class="container mt-5"> <h2 class="text-success text-center">Registration Successful!</h2> <div class="alert alert-success mt-4"> <h4 class="alert-heading">Thank you for registering, @Model.Name!</h4> <p>Here are the details of your registration:</p> <ul class="list-group"> <li class="list-group-item"><strong>Name:</strong> @Model.Name</li> <li class="list-group-item"><strong>Email:</strong> @Model.Email</li> <li class="list-group-item"><strong>Selected Course:</strong> @Model.SelectedCourse</li> <li class="list-group-item"><strong>Skills:</strong> @string.Join(", ", Model.SelectedSkills)</li> <li class="list-group-item"><strong>Gender:</strong> @Model.Gender</li> <li class="list-group-item"><strong>Address:</strong> @Model.Address</li> </ul> <hr /> <p class="mb-0">We have sent a confirmation to your email at <strong>@Model.Email</strong>. Please check your inbox.</p> </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.
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.
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.
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.