Check Box HTML Helper in ASP.NET Core MVC

Check Box HTML Helper in ASP.NET Core MVC

In this article, I am going to discuss How to Generate Check Boxes using CheckBox HTML Helper in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed How to Generate Radio Buttons using HTML Helper in ASP.NET Core MVC.

What is a Check Box?

A checkbox is a graphical user interface (GUI) element that allows users to toggle between two states: checked and unchecked. It’s commonly used in forms and user interfaces to represent binary choices or to allow users to select multiple options from a list.

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 that 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.
  • Labeling: Checkboxes are typically accompanied by labels that provide context and describe what the checkbox represents. Labels are usually placed adjacent to the checkbox, making them clickable to toggle the checkbox state.
  • Use Cases: Checkboxes are commonly used for scenarios where users need to indicate their preferences, select multiple items from a list, or enable/disable certain features or options.
Example of Check Boxes in HTML:
<form>
  <input type="checkbox" id="option1" name="fruit" value="apple">
  <label for="option1">Apple</label><br>
  
  <input type="checkbox" id="option2" name="fruit" value="banana">
  <label for="option2">Banana</label><br>
  
  <input type="checkbox" id="option3" name="fruit" value="orange">
  <label for="option3">Orange</label><br>
</form>

In the above example, the three checkboxes share the same name attribute, fruit, which indicates that they are part of the same group of options. Users can select multiple checkboxes by clicking on the associated labels or the checkboxes themselves. Checkboxes are valuable for gathering user input, setting preferences, and enabling conditional actions based on user choices.

Why do we need CheckBoxes?

When we allow the users to select multiple options from the available options, we need to create a checkbox list. In order to create a checkbox list in the ASP.NET Core MVC Application, we are provided with the CheckBox HTML Helper method.

CheckBox HTML Helper in ASP.NET Core MVC

In ASP.NET Core MVC, the CheckBox HTML Helper is used to generate HTML markup for checkbox inputs within a view. Checkboxes are used when you want users to toggle between two states: checked and unchecked. The CheckBox HTML Helper simplifies the process of creating and binding checkboxes to model properties.

The HtmlHelper class provides two extension methods to generate a <input type=”checkbox”> element in an ASP.NET MVC view. They are as follows:

  1. CheckBox()
  2. CheckBoxFor()

The Html.CheckBox() is a loosely typed method that generates a <input type=”checkbox”> with the specified name, isChecked boolean, and HTML attributes.

The Html.CheckBoxFor() HTML helper method is a strongly typed extension method. It also generates an <input type=”checkbox”> element for the model property, which must be specified using a lambda expression. The CheckBoxFor() HTML Helper method binds a specified model object property to the checkbox element. As a result, it automatically checks or unchecked a checkbox based on that specified model property value.

Generate a Single Checkbox using the CheckBox Helper Method:

To generate a single checkbox, you can use the CheckBox method. This method generates an HTML input element of type “checkbox” and associates it with a property in your model.

@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" />
Generate a Single Checkbox using the CheckBoxFor Helper Method:

To generate a single checkbox, you can use the CheckBoxFor method. 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 with the name NewsLetter.cs and then copy and paste the following code into it.

{
    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 on 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:

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,” and if we don’t select any checkbox, then the message should be “You have not selected any City” displayed.

First, create a class file with the name City.cs and then 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:

@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, both Html.CheckBox and Html.CheckBoxFor methods are HTML Helper methods used to generate checkbox inputs in a view. However, they have distinct purposes and are used in different scenarios. Here’s a comparison of Html.CheckBox and Html.CheckBoxFor:

Html.CheckBox:

This method is used when you want to generate a standalone checkbox input without being directly bound to a model. You need to manage the checked/unchecked state and binding manually.

Syntax: @Html.CheckBox(“name”, isChecked)

  • name: The name attribute of the checkbox.
  • isChecked: A boolean indicating whether the checkbox should be checked.

Example: @Html.CheckBox(“subscribe”, true)

Html.CheckBoxFor:

This method is used when you want to generate a checkbox that is directly bound to a model property. It creates a checkbox input with attributes based on the specified model property and its value. When the form is submitted, the checked/unchecked state is bound to the specified property.

Syntax: @Html.CheckBoxFor(expression)

  • expression: An expression that identifies the model property to which the checkbox is bound.

Example: @Html.CheckBoxFor(m => m.IsSubscribed)

Usage:
  • Html.CheckBox: Used for manual generation of standalone checkboxes that aren’t directly tied to a model.
  • Html.CheckBoxFor: Used when generating checkboxes that are automatically associated with a specific model property, ensuring proper model binding when the form is submitted.
Labelling:
  • Both methods allow you to wrap the checkbox in a <label> element to provide a clickable label for toggling the checkbox state.

The Html.CheckBox is suitable when you want to manage the checkbox state manually and doesn’t need direct model binding. On the other hand, Html.CheckBoxFor is used when you want to generate checkboxes that are directly bound to a specific model property, ensuring automatic model binding when the form is submitted.

In the next article, I am going to discuss ListBox HTML Helper in ASP.NET Core MVC application. In this article, I explain How to Create a Check Box HTML Helper in ASP.NET Core MVC Application step by step 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 *