Back to: ASP.NET Core Tutorials For Beginners and Professionals
Check Box HTML Helper in ASP.NET Core MVC
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.
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.
Key Characteristics of Check Boxes:
- 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.
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:
<form action="/submit-form" method="post"> <label> <input type="checkbox" name="interest" value="music"> Music </label> <label> <input type="checkbox" name="interest" value="books"> Books </label> <label> <input type="checkbox" name="interest" value="sports"> Sports </label> <input type="submit" value="Submit"> </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.
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.
CheckBox HTML Helper
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,
- 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; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public string UpdateProfile(bool SubscribeToNewsletter) { if(SubscribeToNewsletter) { return "You Subscribed to Newsletter"; } else { return "You Havenot Subscribed to Newsletter"; } } } }
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"; } <h2>Update Profile Page</h2> <form asp-action="UpdateProfile" asp-controller="Home" method="post"> @* 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 *@ @Html.CheckBox("SubscribeToNewsletter", false, new { @class = "form-check-input" }) @* Generates a checkbox input element First argument "SubscribeToNewsletter" is the name of the checkbox, which will be used to retrieve the value in the controller action. Second argument "false" sets the default value of the checkbox to unchecked. Third argument is an anonymous object that assigns a CSS class "form-check-input" for Bootstrap styling. *@ <label class="form-check-label" for="SubscribeToNewsletter"> 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> <button type="submit" class="btn btn-primary">Save</button> @* A submit button with Bootstrap styling. When clicked, the form data is sent to the server to the specified action method "UpdateProfile" in the "Home" controller. *@ </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:
using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public string Register(bool AcceptTerms) { if(AcceptTerms) { return "You Accept the Terms and Conditions"; } else { return "You Havenot Accept the Terms and Conditions"; } } } }
Modify 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. 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> <form asp-action="Register" asp-controller="Home" method="post"> @* The form sends a POST request to the "Register" action method in the "Home" controller when submitted. *@ <div class="form-check"> @* A Bootstrap container with the "form-check" class to properly style checkboxes. *@ @Html.CheckBox("AcceptTerms", false, new { @class = "form-check-input", id = "AcceptTerms" }) @* Generates a checkbox input element with the name "AcceptTerms". The second argument "false" sets the checkbox to unchecked by default. The third argument is an anonymous object that sets the HTML attributes for the checkbox: class: Bootstrap class "form-check-input" for styling. *@ <label class="form-check-label" for="AcceptTerms"> I accept the terms and conditions </label> @* The label associated with the checkbox, containing descriptive text. The "for" attribute is linked to the checkbox by its ID, "AcceptTerms", ensuring that clicking the label checks the checkbox. *@ </div> <button type="submit" class="btn btn-primary" disabled id="submitBtn">Register</button> @* A Bootstrap-styled submit button with the class "btn btn-primary". 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> // jQuery library is included to handle DOM manipulations and event handling. $(document).ready(function () { // This function executes when the document is fully loaded and ready. $('#AcceptTerms').click(function () { // Attaches a click event handler to the checkbox with ID "AcceptTerms". // Checks if the checkbox is selected. if ($(this).is(':checked')) { // If the checkbox is checked, it removes the "disabled" attribute from the submit button, enabling it. $('#submitBtn').removeAttr('disabled'); } 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.
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 { public class SecuritySettingsViewModel { public bool EnableTwoFactorAuth { get; set; } } }
Modifying Home Controller:
Next, modify the Home Controller as follows:
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { //Current Settings SecuritySettingsViewModel settings = new SecuritySettingsViewModel() { EnableTwoFactorAuth = false }; return View(); } [HttpPost] public string UpdateSecuritySettings(SecuritySettingsViewModel settings) { if(settings.EnableTwoFactorAuth) { return "You Enable Two Factor Authentication"; } else { return "You Disabled Two Factor Authentication"; } } } }
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"; } <h2>Enable/Disable Two Factor Authentication</h2> <form asp-action="UpdateSecuritySettings" asp-controller="Home" method="post"> <div class="form-check"> @Html.CheckBoxFor(model => model.EnableTwoFactorAuth, new { @class = "form-check-input" }) <label class="form-check-label" for="enableTwoFactorAuth"> Enable Two-Factor Authentication </label> </div> <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.
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.
Creating Login Model:
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 { public class LoginViewModel { public string UserName { get; set; } public string Password { get; set; } public bool RememberMe { get; set; } } }
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 { public class AccountController : Controller { [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public IActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { // Perform login logic here (e.g., authenticate the user) // Use the RememberMe flag as needed in authentication logic if (model.RememberMe) { // Set cookie or other logic for remembering the user } return RedirectToAction("Index", "Home"); } // If invalid, redisplay the form 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> <form asp-action="Login" asp-controller="Home" method="post"> <div class="form-group"> <label for="UserName">User Name</label> <input type="text" class="form-control" id="UserName" asp-for="UserName" placeholder="Enter your username" /> <span asp-validation-for="UserName" class="text-danger"></span> </div> <div class="form-group"> <label for="Password">Password</label> <input type="password" class="form-control" id="Password" asp-for="Password" placeholder="Enter your password" /> <span asp-validation-for="Password" class="text-danger"></span> </div> <div class="form-check"> @Html.CheckBoxFor(model => model.RememberMe, new { @class = "form-check-input" }) <label class="form-check-label" for="RememberMe"> Remember me </label> </div> <button type="submit" class="btn btn-primary">Login</button> </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.
How is it going to work?
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.
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.
Define the Model:
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 { public class ProgrammingLanguagesViewModel { public List<LanguageOption> LanguageOptions { get; set; } } public class LanguageOption { public bool IsSelected { get; set; } public string LanguageName { get; set; } } }
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 { public class LanguageController : Controller { public IActionResult SelectLanguages() { var model = new ProgrammingLanguagesViewModel { LanguageOptions = new List<LanguageOption> { new LanguageOption { IsSelected = false, LanguageName = "C#" }, new LanguageOption { IsSelected = false, LanguageName = "ASP.NET Core" }, new LanguageOption { IsSelected = false, LanguageName = "Python" }, new LanguageOption { IsSelected = false, LanguageName = "Java" }, new LanguageOption { IsSelected = false, LanguageName = "Ruby" }, new LanguageOption { IsSelected = false, LanguageName = "C++" } } }; return View(model); } [HttpPost] public IActionResult SubmitLanguages(ProgrammingLanguagesViewModel model) { // Filter the selected languages var selectedLanguages = model.LanguageOptions .Where(option => option.IsSelected) .Select(option => option.LanguageName) .ToList(); // Do something with the selected languages (e.g., display them on a results page) ViewBag.SelectedLanguages = selectedLanguages; return View("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"; } <h2>Select Your Preferred Programming Languages</h2> <form asp-action="SubmitLanguages" asp-controller="Language" method="post"> @* This begins an HTML form element. The 'asp-action' attribute specifies that the form will submit data to the 'SubmitLanguages' action method in the 'Language' controller. The 'method="post"' specifies that the form will use the HTTP POST method to send data to the server. *@ @for (int i = 0; i < Model.LanguageOptions.Count; i++) { // A for-loop that iterates over the 'LanguageOptions' list in the bound model (ProgrammingLanguagesViewModel). // 'LanguageOptions' is a collection of LanguageOption objects, each representing a programming language. <div class="form-group"> @Html.CheckBoxFor(m => m.LanguageOptions[i].IsSelected) @* 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> @* This creates an HTML label element next to the checkbox. It displays the name of the programming language by accessing the 'LanguageName' property of the current LanguageOption object. *@ @Html.HiddenFor(m => m.LanguageOptions[i].LanguageName) @* 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 though it is not visible on the form. *@ </div> } <button type="submit" class="btn btn-primary">Submit</button> </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"; } <h2>Selected Programming Languages</h2> @if (Model.Count == 0) { <p>No languages selected.</p> } else { <ul> @foreach (var language in Model) { <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:
Strongly Typed vs. Weakly-Typed:
- 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: It doesn’t bind directly to a model property. If you want to bind it to a property, you will need to handle the binding when manually processing the form submission.
- Html.CheckBoxFor: This is automatically tied to the model’s boolean property, so when the form is submitted, the value of the checkbox is bound back to the model without any additional code.
IntelliSense Support:
- 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 Application with examples. I hope you enjoy this Check Box HTML Helper in ASP.NET Core MVC article.