CheckBox Helper in MVC

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.   
  7. namespace CheckBoxApp_MVC.Controllers  
  8. {  
  9.     public class EmployeeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Employee/  
  13.         public ActionResult Index()  
  14.         {  
  15.             List<SelectListItem> items = new List<SelectListItem>();  
  16.             items.Add(new SelectListItem { Text = "IT", Value = "0" });  
  17.             items.Add(new SelectListItem { Text = "HR", Value = "1" });  
  18.             items.Add(new SelectListItem { Text = "Management", Value = "2" });  
  19.             ViewBag.List = items;  
  20.             return View();  
  21.         }  
  22.     }  
  23. }

Index.cshtml

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

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!