CheckBox For Helper to Handle HttpPost in MVC

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.   
  9. namespace CheckBoxForMVCPost_App.Controllers  
  10. {  
  11.     public class EmployeeController : Controller  
  12.     {  
  13.         EmployeeEntities db = new EmployeeEntities();  
  14.         //  
  15.         // GET: /Employee/  
  16.         public ActionResult Index()  
  17.         {  
  18.             return View(db.Departments.ToList());  
  19.         }  
  20.   
  21.         [HttpPost]  
  22.         public string Index(IEnumerable<Department> model)  
  23.         {  
  24.             StringBuilder sb = new StringBuilder();  
  25.             foreach (var mode in model)  
  26.             {  
  27.                 if (mode.IsSelected)  
  28.                 {  
  29.                     sb.Append("Selected Value is : <b>" + mode.DepartmentName + "</b>");  
  30.                     sb.Append("<br />");  
  31.                 }  
  32.   
  33.             }  
  34.             return sb.ToString();  
  35.         }  
  36.   
  37.     }  
  38. }

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. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))  
  10. {  
  11.   
  12.     for (int i = 0; i < Model.Count; i++)  
  13.     {  
  14.         @Html.HiddenFor(m => m[i].DepartmentName)  
  15.         @Html.CheckBoxFor(m => m[i].IsSelected)  
  16.         @Html.DisplayTextFor(m => m[i].DepartmentName)  
  17.         <br />  
  18.     }  
  19.     <br />  
  20.     <input type="submit" value="Submit" />  
  21. }  
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.

Up Next
    Ebook Download
    View all
    Learn
    View all
    MVC Corporation is consulting and IT services based company.