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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace CheckBoxMVCPost.Controllers
- {
- public class EmployeeController : Controller
- {
-
-
- public ActionResult Index()
- {
- List<SelectListItem> items = new List<SelectListItem>();
- items.Add(new SelectListItem { Text = "IT", Value = "0" });
- items.Add(new SelectListItem { Text = "HR", Value = "1" });
- items.Add(new SelectListItem { Text = "Management", Value = "2" });
- ViewBag.List = items;
- return View();
- }
-
- [HttpPost]
- public string Index(string checkBoxItems)
- {
- if (string.IsNullOrEmpty(checkBoxItems))
- {
- return "Invalid Selection";
- }
- else
- {
- return "Selected Value is" + checkBoxItems;
- }
- }
- }
- }
Add a View.
Figure 5: Add View
Figure 6: Index View
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
- @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
- {
- foreach (SelectListItem item in ViewBag.List)
- {
- <input type="checkbox" name="checkBoxItems" value="@item.Text" />@item.Text
- <br />
- }
- <br />
- <input type="submit" value="Submit" />
- }
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!