The Checkbox control in MVC
Here, In this Article, We are going to explain how to create checkbox control and how to get the selected checkboxes value in MVC.
Here in the Model class, I have created a property named Hobbies that is of type List<string>, that return some natural hobbies such as Cricket, Football, Hockey stored in a property as I have mentioned below;
using System.Collections.Generic;
using System.Web;
namespace CheckBoxMVC.Models
{
public class ModelClass
{
public List<string> Hobbies
{
get
{
List<string> hobby = new List<string>();
hobby.Add("Cricket");
hobby.Add("Football");
hobby.Add("Hockey");
return hobby;
}
}
}
}
After completing the section of Model, here in the Controller class, I have created two Action methods.
First Index method that returns a View along with the object of ModelClass and in the second action method i.e.
The show which checks the state of checkbox and stores selected checkbox value in a variable.
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using CheckBoxMVC.Models;
namespace CheckBoxMVC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new ModelClass());
}
[HttpPost]
public string Show(FormCollection postedForm, ModelClass model)
{
string val = "";
foreach (var category in model.Hobbies)
{
if (postedForm[category].ToString().Contains("true"))
{
val = val + " " + category;
}
}
return "Selcted hobbies are: <b>" + val + "</b>";
}
}
}
After performing the above tasks, you have to create the checkbox in a View which displays the hobby that is returned by a property of Model.
Also, create a submit button on click of which selected hobbies are displayed or we can say selected checkboxes values are displayed.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<CheckBoxMVC.Models.ModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<% using (Html.BeginForm("Show", "Home", FormMethod.Post))
{ %>
<div>
<b>Select Hobbies : </b>
<% foreach (string hobby in Model.Hobbies)
{ %>
<%: Html.CheckBox(hobby)%><%: hobby%>
<%} %>
<br /><br />
<input type="submit" value="Submit" />
</div>
<%} %>
</body>
</html>
After performing the above tasks, we can see the output of our application in a browser with multiple checkboxes.

When a submit button is pressed selected hobbies are displayed.

By using the above process you can simply learn how to create a checkbox and get selected checkbox value in MVC.
Leave Comment
16 Comments