Check Box HTML Helper in ASP.NET Core MVC

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.

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 either checked (selected) or unchecked (not selected). CheckBoxes are used when there is one or more options that can be selected independently, and submitting the form can proceed with any combination of options selected or none at all.

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 of HTML code 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 among music, books, and sports. The form will send the values of the selected interests to the server when submitted. CheckBoxes are useful in web applications for various purposes, such as settings that can be turned on or off independently, multiple selections from a list of options, and features like agreeing to terms and conditions.

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 of each other, meaning each checkbox represents a separate choice, and multiple checkboxes can be checked simultaneously.
  • HTML Structure: In HTML, a checkbox is represented by an <input> element with a type attribute set to “checkbox”. The value attribute defines the value that will be sent to the server when the checkbox is checked and the form is submitted.
  • Use Cases: 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 you want to specify the name of the form field manually, while 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.

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

The CheckBox HTML Helper in ASP.NET Core MVC is a server-side helper used to generate a checkbox input (a boolean input) in a form that is being rendered as HTML. The CheckBox HTML Helper is specifically used for generating checkboxes that the user can check or uncheck. These checkboxes are often used for true/false or yes/no options.

Generate a Single Checkbox using the CheckBox Helper Method:

You can use the CheckBox method to generate a single checkbox. This method generates an HTML input element of type “checkbox” and associates it with a property in your model. If you need more manual control or aren’t using a strongly-typed model, you can use Html.CheckBox.

@Html.CheckBox("IsSubscribed")
Subscribe to Newsletter

It will generate the following HTML Element.

<input id="IsSubscribed" name="IsSubscribed" type="checkbox" value="true" /><input name="IsSubscribed" type="hidden" value="false" />
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 for a form. The CheckBoxFor helper binds a model property to a checkbox input, making it easier to submit form data, including validation and model binding back to the server.

The CheckBoxFor method is used within a Razor view and requires a lambda expression specifying the model property to which it is bound. When the form is submitted, the value of the checkbox (whether it is checked or not) is automatically bound to the model property, facilitating the handling of user input on the server side.

Generate a Single Checkbox using the CheckBoxFor Helper Method:

To generate a single checkbox, you can use the CheckBoxFor method. This approach binds the checkbox to a specific property on your model. It’s strongly typed and recommended for most scenarios where you’re working with model data. This method generates an HTML input element of type “checkbox” and associates it with a property in your model. So, let us first create a class file named NewsLetter.cs and then copy and paste the following code into it.

namespace HTML_HELPER.Models
{
    public class NewsLetter
    {
        public bool IsSubscribed { get; set; }
    }
}

Next, modify the Home Controller as follows:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            NewsLetter model = new NewsLetter();
            model.IsSubscribed = false;
            return View(model);
        }

        [HttpPost]
        public string Index(NewsLetter model)
        {
            if (model.IsSubscribed)
            {
                return "You Subscribed to our Newsletter";
            }
            else
            {
                return "You Have Not Subscribed to our Newsletter";
            }
        }
    }
}

Next, modify the Index.cshtml file as follows:

@model HTML_HELPER.Models.NewsLetter
@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(model => model.IsSubscribed)
    <label for="IsSubscribed">Subscribe to Newsletter</label>
    <br/><br/>
    <input type="submit" value="Submit" />
}

In this example, IsSubscribed is a boolean property in the model that will hold the checked/unchecked state of the checkbox. The CheckBoxFor method takes an expression as an argument to define the model property. When the form is submitted, the checked/unchecked state will be bound to the specified model property.

Now, run the application and click the Submit button without checking the check box. Notice that you are getting a message stating You Have Not Subscribed to our Newsletter. On the other hand, if you check the check box and then click the Submit button, you will see the You Subscribed to our Newsletter message.

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. Here’s a step-by-step guide to demonstrate how to achieve this: We want to create the interfaces with the following checkboxes.

Generating Multiple Check Boxes using CheckBoxFor Helper Method

Our requirement is when we select the checkboxes and click on the submit button. All the selected checkbox values should display as “You selected – Checkbox Values,” if we don’t select any checkbox, then the message should be “You have not selected any City” displayed.

First, create a class file named City.cs and copy and paste the following code into it.

namespace HTML_HELPER.Models
{
    public class City
    {
        public int CityId { get; set; }
        public string? CityName { get; set; }
        public bool IsSelected { get; set; }
    }
}

Next, modify the Home Controller as follows:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            List<City> CityList = new List<City>()
            {
                new City(){ CityId = 1, CityName = "London", IsSelected = false },
                new City(){ CityId = 2, CityName = "New York", IsSelected = false },
                new City(){ CityId = 3, CityName = "Sydney", IsSelected = true },
                new City(){ CityId = 4, CityName = "Mumbai", IsSelected = false },
                new City(){ CityId = 5, CityName = "Cambridge", IsSelected = false },
                new City(){ CityId = 6, CityName = "Delhi", IsSelected = false },
                new City(){ CityId = 7, CityName = "Hyderabad", IsSelected = true }
            };

            return View(CityList);
        }

        [HttpPost]
        public string Index(IEnumerable<City> cities)
        {
            if (cities.Count(x => x.IsSelected) == 0)
            {
                return "You have not selected any City";
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("You Selected - ");
                foreach (City city in cities)
                {
                    if (city.IsSelected)
                    {
                        sb.Append(city.CityName + ", ");
                    }
                }
                sb.Remove(sb.ToString().LastIndexOf(","), 1);
                return sb.ToString();
            }
        }
    }
}

Next, modify the Index.cshtml file as follows:

In the below view, CheckBoxFor is used inside a loop to render checkboxes for each item in the collection. A hidden field is also used to maintain each item’s ID. When the form is submitted, the selected checkboxes are sent to the corresponding action method.

@model List<HTML_HELPER.Models.City>
@{
    ViewBag.Title = "Index";
    Layout = null;
}

@using (Html.BeginForm())
{
    for (var i = 0; i < Model.Count(); i++)
    {
        <table>
            <tr>
                <td>
                    @Html.HiddenFor(it => it[i].CityId)
                    @Html.HiddenFor(it => it[i].CityName)
                    @Html.DisplayFor(it => it[i].CityName)
                </td>
                <td>
                    @Html.CheckBoxFor(it => it[i].IsSelected, new { Style = "vertical-align:3px}" })
                </td>
            </tr>
        </table>
    }
    <input id="Submit1" type="submit" value="submit" />
}

Note:

  • HiddenFor: Hidden Field to maintain the ID.
  • DisplayFor: DisplayFor displays the checkbox name (text).
  • CheckboxFor: CheckBoxFor displays the checkbox.

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?

In ASP.NET Core MVC, CheckBox and CheckBoxFor are HTML helper methods that generate HTML checkbox input elements. Despite their similar purpose, these two helpers differ mainly in how they are used and their integration with model properties.

  • Model Binding: The most significant difference is that CheckBoxFor uses a lambda expression to bind the checkbox directly to a model property, ensuring that the state of the checkbox is synced with that property. CheckBox, on the other hand, requires manual handling of its state and does not bind directly to a model property.
  • Syntax and Usage: CheckBoxFor takes a lambda expression that points to a model property, while CheckBox takes a string name and a boolean state. This makes CheckBoxFor more strongly typed, reducing errors and simplifying model binding.
  • Intended Use: CheckBox is more flexible and can be used when the checkbox does not directly correspond to a model property. CheckBoxFor is specifically designed for scenarios where the checkbox is a direct representation of a model property, facilitating easier data binding and validation.
  • Use Cases: If you are working with a view model and want to ensure strong typing and model binding and simplify form submission and validation, CheckBoxFor is the preferred option. If you need a checkbox that is not directly tied to a model or requires more control over the input’s attributes, CheckBox offers the necessary flexibility.

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.

Leave a Reply

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