CheckBox Helper to Handle HttpPost in MVC

Introduction

This article shows how to use a CheckBox helper to handle HttpPost in MVC applications.

Create an ASP.Net Web Application.

 
Figure 1: Web Application

Add an Employee Controller.

 
Figure 2: Add Controller
 
 
Figure 3: MVC 5 Controller Empty
 
 
Figure 4: Employee 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 CheckBoxMVCPost.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.         [HttpPost]  
  24.         public string Index(string checkBoxItems)  
  25.         {  
  26.             if (string.IsNullOrEmpty(checkBoxItems))  
  27.             {  
  28.                 return "Invalid Selection";  
  29.             }  
  30.             else  
  31.             {  
  32.                 return "Selected Value is" + checkBoxItems;  
  33.             }  
  34.         }  
  35.     }  
  36. }

Add a View.

 
Figure 5: Add View
 
 
Figure 6: Index View

Index.cshtml

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))  
  7. {  
  8.     foreach (SelectListItem item in ViewBag.List)  
  9.     {  
  10.         <input type="checkbox" name="checkBoxItems" value="@item.Text" />@item.Text  
  11.         <br />  
  12.     }  
  13.     <br />  
  14.     <input type="submit" value="Submit" />  
  15. }

The following screenshot shows the output of the application.

 
Figure 7: Index View Output
 
 
Figure 8: Index View Output HttpPost

Summary

In this article we saw how to use a CheckBox helper to handle HttpPost in MVC application.
Happy coding!