CheckBoxFor Helper in MVC

Introduction

This article shows how to use a CheckBoxFor helper in MVC applications.

Create an ASP.Net Web Application as in Figure 1.

 

Figure 1: Web application

Choose MVC template as in Figure 2.

 

Figure 2: MVC template

Add an Employee Controller as in Figures 3, 4 and 5.

 

Figure 3: Add controller

 

Figure 4: MVC controller - empty

 

Figure 5: EmployeeController

EmployeeController.cs

  1. using CheckBoxForMVC_App.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace CheckBoxForMVC_App.Controllers  
  9. {  
  10.     public class EmployeeController : Controller  
  11.     {  
  12.         EmployeeEntities db = new EmployeeEntities();  
  13.         //  
  14.         // GET: /Employee/  
  15.         public ActionResult Index()  
  16.         {  
  17.             return View(db.Departments.ToList());  
  18.         }  
  19.     }  
  20. }  
Set up Entity Framework as in Figures 6, 7 and 8.
 

Figure 6: Add an ADO.Net Entity Framework.

 

Figure 7: Connection setting.

 

Figure 8: Select tables

Add the View as in Figures 9 and 10.

 

Figure 9: Add View

 

Figure 10: Index View

Index.cshtml

  1. @model IEnumerable<CheckBoxForMVC_App.Models.Department>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. @foreach (var item in Model)  
  10. {  
  11.     @Html.CheckBoxFor(model => item.IsSelected)@item.DepartmentName  
  12.     <br />  
  13. }  
The output of the application is as in the following.
 

Figure 11: Index

Summary

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