CheckBox HTML Helper in ASP.NET MVC

Creating CheckBox using CheckBox HTML Helper in ASP.NET MVC

In this article, I am going to discuss how to create a checkbox using CheckBox HTML Helper in the ASP.NET MVC application. Please read our previous article where we discussed how to create radio buttons using the RadioButton HTML Helper in ASP.NET MVC Application. As part of this article, we are going to discuss the following pointers.

  1. Why we need CheckBox?
  2. Understanding the CheckBox HTML Helper in ASP.NET MVC Application
  3. CheckBox HTML Helper in MVC Application
Why we need CheckBox?

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

Understanding the CheckBox HTML Helper in ASP.NET MVC Application

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 which 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 needs to 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 checked or unchecked a checkbox based on that specified model property value.

CheckBox HTML Helper in MVC Application:

To understand the CheckBox HTML Helper in MVC, we are going to use the following “City” table.

CheckBox HTML Helper in MVC

In the user interface, we need to create checkboxes for each city as shown in the below image.

ASP.NET MVC CheckBox HTML Helper

Our requirement is when we select the checkboxes and click on the submit button then 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” display.

Please use the following SQL script to create table City and populate with the required test data.
CREATE TABLE City
(
  City_ID INT IDENTITY PRIMARY KEY,
  City_Name NVARCHAR(100) NOT NULL,
  IsSelected BIT NOT NULL
)

Insert into City values ('London', 0)
Insert into City values ('New York', 0)
Insert into City values ('Sydney', 1)
Insert into City values ('Mumbai', 0)
Insert into City values ('Cambridge', 0)
Insert into City values ('Delhi', 0)
Insert into City values ('Hyderabad', 1)

Let’s add the ADO.NET data model to retrieve data from the database

CheckBox HTML Helper in ASP.NET MVC

Creating Controller:

Right-click on the “Controllers” folder and then add a controller with the name “HomeController”. Once you create the controller then copy and paste the following code in it.

namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            CityDBContext dbContext = new CityDBContext();
            return View(dbContext.Cities.ToList());
        }

        [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.City_Name + ", ");
                    }
                }
                sb.Remove(sb.ToString().LastIndexOf(","), 1);
                return sb.ToString();
            }
        }
    }
}
Note:
  1. HiddenFor: Hidden for maintains the ID.
  2. DisplayFor: DisplayFor displays the checkbox name (text).
  3. CheckboxFor: CheckboxFor displays the checkbox.
Create the Index View and then copy and paste the following code in it
@model List<HTML_HELPER.Models.City>
@{
    ViewBag.Title = "Index";
}

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

    }
    <input id="Submit1" type="submit" value="submit" />
}

That’s it. We are done with our implementation. Now run the application and test the requirement and you will see it is working as expected.

In the next article, I am going to discuss the ListBox HTML Helper in the ASP.NET MVC application. Here, in this article, I try to explain CheckBox HTML Helper in MVC application step by step with a real-time example.