Introduction

This article shows how to use the checkbox helper in MVC applications.

Create an ASP.Net web application


Figure 1 We Application

Choose MVC template


Figure 2 MVC Template

Add an employee controller


Figure 3 Employee Controller


Figure 4 Add Controller

Employeecontroller.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace CheckBoxApp_MVC.Controllers
  7. {
  8. public class EmployeeController : Controller
  9. {
  10. //
  11. // GET: /Employee/
  12. public ActionResult Index()
  13. {
  14. List<SelectListItem> items = new List<SelectListItem>();
  15. items.Add(new SelectListItem { Text = "IT", Value = "0" });
  16. items.Add(new SelectListItem { Text = "HR", Value = "1" });
  17. items.Add(new SelectListItem { Text = "Management", Value = "2" });
  18. ViewBag.List = items;
  19. return View();
  20. }
  21. }
  22. }

Index.cshtml

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Index</h2>
  5. @foreach (SelectListItem item in ViewBag.List)
  6. {
  7. @Html.CheckBox(item.Text)@item.Text
  8. <br />
  9. }

The following is the output of the application.


Figure 5 Index

Summary

In this article we saw how to use the checkbox helper in MVC applications. Happy coding!