Introduction

This article shows how to use a CheckBoxFor helper handling HttpPost 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: Employee Controller

EmployeeController.cs

  1. using CheckBoxForMVCPost_App.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. namespace CheckBoxForMVCPost_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. [HttpPost]
  20. public string Index(IEnumerable<Department> model)
  21. {
  22. StringBuilder sb = new StringBuilder();
  23. foreach (var mode in model)
  24. {
  25. if (mode.IsSelected)
  26. {
  27. sb.Append("Selected Value is : <b>" + mode.DepartmentName + "</b>");
  28. sb.Append("<br />");
  29. }
  30. }
  31. return sb.ToString();
  32. }
  33. }
  34. }

Set up the Entity Framework as in Figures 6, 7 and 8.


Figure 6: Add ADO.NET Entity Framework

Figure 7: Connection Setting

Figure 8: Select Tables

Add a View as in Figures 9 and 10.


Figure 9: Add View

Figure 10: Index View

Index.cshtml

  1. @model IList<CheckBoxForMVCPost_App.Models.Department>
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <h2>Index</h2>
  6. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
  7. {
  8. for (int i = 0; i < Model.Count; i++)
  9. {
  10. @Html.HiddenFor(m => m[i].DepartmentName)
  11. @Html.CheckBoxFor(m => m[i].IsSelected)
  12. @Html.DisplayTextFor(m => m[i].DepartmentName)
  13. <br />
  14. }
  15. <br />
  16. <input type="submit" value="Submit" />
  17. }
The output of the application is as in Figures 11 and 12.

Figure 11: Index

Figure 12: Selected Values

Summary

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