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. namespace CheckBoxMVCPost.Controllers
  7. {
  8. public class EmployeeController : Controller
  9. {
  10. //
  11. // GET: /Employee/
  12. public ActionResult Index()
  13. {
  14. List<SelectListItem> items = new List<SelectListItem>();
  15. items.Add(new SelectListItem { Text = "IT", Value = "0" });
  16. items.Add(new SelectListItem { Text = "HR", Value = "1" });
  17. items.Add(new SelectListItem { Text = "Management", Value = "2" });
  18. ViewBag.List = items;
  19. return View();
  20. }
  21. [HttpPost]
  22. public string Index(string checkBoxItems)
  23. {
  24. if (string.IsNullOrEmpty(checkBoxItems))
  25. {
  26. return "Invalid Selection";
  27. }
  28. else
  29. {
  30. return "Selected Value is" + checkBoxItems;
  31. }
  32. }
  33. }
  34. }

Add a View.


Figure 5: Add View

Figure 6: Index View

Index.cshtml

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

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!