CheckBoxList in ASP.NET MVC 4

When we use MVC in ASP.Net, we are not using server-side webform controls. We always use @Html helper controls or simple HTML controls, for example
 
<input type="textbox" Id="txtName"/>.

So the question always arises, how to create a Checkboxlist in MVC. We can build this in ASP.Net webforms very easily using built-in server controls. But how to do this in MVC.

Checkbox-List.jpg

Figure: Checkbox List

So in this article, I explain how to create a checkboxlist in MVC.

Please follow these steps:

Step 1

Click "File" -> "New" -> "Project...".

Create-New-Mvc-Project.jpg

Figure 1: Create New MVC Project

Step 2


Select "ASP.Net MVC4 WebApplication", provide your Project Name, for example I used "CheckboxListDemo", then click "Ok".

Step 3

Now select "Internet Application", and then click "Ok".

Select-Project-Template.jpg

Figure 2: Select Project Template

Step 4

For this application we will create a Model. So right-click on the Model folder then click on "Add" -> "Class".

Add-a-New-model.jpg

Figure 3: Add a New model.

Here we will create "StudentModel". Now click on the "Add" Button.

Now add the following code.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6.      
  7. namespace CheckboxListDemo.Models    
  8. {    
  9.     public class StudentModel    
  10.     {    
  11.       public IList<SelectListItem> StudentNames { getset; }    
  12.     }    
  13. }   

In the code above, I create am "IList<SelectListItem>" type propery. This SelectListItem returns both text and a value that is helpful for lists (like Dropdownlist, Listbox etcetera).

We will now write the code for a Controller.

Right-click on the Controller folder then seelct "Add" >> "Controller".

Add-New-Controller.jpg

Figure 4: Add New Controller

Now this is our Empty MVC Controller, click on the "Add" button. We will now write the code.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. using CheckboxListDemo.Models;    
  7.      
  8. namespace CheckboxListDemo.Controllers    
  9. {    
  10.     public class StudentController : Controller    
  11.     {  
  12.         public ActionResult Index()    
  13.         {    
  14.             return View();    
  15.         }   
  16.         // GET: /Student/   
  17.         public ActionResult Student()    
  18.         {    
  19.             StudentModel objStudentModel = new StudentModel();    
  20.             List<SelectListItem> names = new List<SelectListItem>();    
  21.             names.Add(new SelectListItem { Text = "Sourabh", Value = "1" });    
  22.             names.Add(new SelectListItem { Text = "Surbhee", Value = "2" });    
  23.             names.Add(new SelectListItem { Text = "Vinay", Value = "3" });    
  24.             names.Add(new SelectListItem { Text = "Tushar", Value = "4" });    
  25.      names.Add(new SelectListItem { Text = "John", Value = "5" });    
  26.             names.Add(new SelectListItem { Text = "Tom", Value = "6" });    
  27.             objStudentModel.StudentNames = names;     
  28.             return View(objStudentModel);    
  29.         }   
  30.     }    
  31. } 

In the code above, I create a new ActionMethod and Student. In this Action Method , I am returning a model, that has a list of student names.

If you notice in the code above, I use SelectListItem and SelectListItem having the two properties Text and Value, that are helpful for a list like Dropdownlist, Listbox etcetera.

Now add a new view, so right-click and click on "Add View".

Add-View.jpg

Figure 5: Add View

Now click on the "Add" button. Now add the following code:

Student.cshtml

  1. @model CheckboxListDemo.Models.StudentModel    
  2. @{    
  3.     ViewBag.Title = "Student";    
  4. }  
  5. <h2>Student</h2>  
  6. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  7. <script>    
  8.     $(document).ready(function () {    
  9.         $('.chkclass').click(function () {  
  10.             var getchkid = $(this).attr('id');    
  11.             var isChecked = $('#' + getchkid).is(':checked');  
  12.             if ($('#' + getchkid).is(':checked') == true) {    
  13.                 $('#td' + $(this).val()).css("color""white");    
  14.                 $('#td' + $(this).val()).css("background-color""blue");    
  15.             }    
  16.             else {    
  17.                 $('#td' + $(this).val()).css("color""black");    
  18.                 $('#td' + $(this).val()).css("background-color""white");    
  19.             }    
  20.         });  
  21.         $('#bttn_Click').click(function () {  
  22.             var studentListVal = null;    
  23.             studentListVal = [];    
  24.                 
  25.             $('input:checkbox:checked').each(function () {    
  26.                 studentListVal.push($(this).attr('value'));    
  27.             });  
  28.             $.ajax({    
  29.                 type: "post",    
  30.                 url: "/Student/Studentl",    
  31.                 data: { Name: studentListVal },    
  32.                 datatype: "json",    
  33.                 traditional: true,    
  34.                 success: function (data) {         
  35.                     var selectedIds;    
  36.                     for (var i = 0; i < data.success.length; i++)    
  37.                     {    
  38.                         if (selectedIds != undefined) {    
  39.                             selectedIds = selectedIds + " " + data.success[i];    
  40.                         }    
  41.                         else {    
  42.                             selectedIds = data.success[i];    
  43.                         }    
  44.                     }    
  45.                     alert('You have Selected Student Ids- '+selectedIds);    
  46.                 }    
  47.             });  
  48.         });  
  49.     });  
  50. </script>  
  51. <div id="divStudentlist" style="height: 100px; overflow: auto;border:solid; width:150px;">    
  52. @foreach (var names in @Model.StudentNames)    
  53. {    
  54.     var checkBoxId = "chk" + names.Value;    
  55.     var tdId = "td" + names.Value;    
  56.                     <table width="100%">    
  57.                         <tr >    
  58.                             <td width="20px">    
  59.                                 <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />    
  60.                             </td>    
  61.                             <td id="@tdId"  width="100px">    
  62.                                 @names.Text    
  63.                             </td>    
  64.                         </tr>          
  65.                     </table>  
  66. }    
  67. </div>  
  68. <div>    
  69.     <input type="button" id="bttn_Click" value="Send Checked value to Controller" />    
  70. </div> 
StudentController.cs
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. using CheckboxListDemo.Models;    
  7.     
  8. namespace CheckboxListDemo.Controllers    
  9. {    
  10.     public class StudentController : Controller    
  11.     {    
  12.         //    
  13.         // GET: /Student/    
  14.     
  15.         public ActionResult Index()    
  16.         {    
  17.             return View();    
  18.         }    
  19.     
  20.         public ActionResult Student()    
  21.         {    
  22.             StudentModel objStudentModel = new StudentModel();    
  23.             List<SelectListItem> names = new List<SelectListItem>();    
  24.             names.Add(new SelectListItem { Text = "Sourabh", Value = "1" });    
  25.             names.Add(new SelectListItem { Text = "Surbhee", Value = "2" });    
  26.             names.Add(new SelectListItem { Text = "Vinay", Value = "3" });    
  27.             names.Add(new SelectListItem { Text = "Tushar", Value = "4" });    
  28.             objStudentModel.StudentNames = names;    
  29.                 
  30.             return View(objStudentModel);    
  31.         }    
  32.     
  33.         [HttpPost]    
  34.         public ActionResult Studentl(string[] Name)    
  35.         {    
  36.             return Json(new { success = Name });    
  37.         }  
  38.     }  
  39. }  
Your view is now created and you are ready to run your CheckboxList Program. So Press F5 and run your code.

CheckboxList

You might now wonder how this blue color appears in the background when I check a checkbox and disappears when I uncheck a checkbox. I did this using jQuery. But first you must understand how this checkbox list is created.

Look at the following code:
  1. <div id="divstudentlist" style="height: 110px; overflow: auto;border:solid; width:150px;">     
  2. @foreach (var names in @Model.StudentNames)     
  3. {     
  4.     var checkBoxId = "chk" + names.Value;     
  5.     var tdId = "td" + names.Value;     
  6.                     <table width="100%">     
  7.                         <tr >     
  8.                             <td width="20px">     
  9.                                 <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />     
  10.                             </td>     
  11.                             <td id="@tdId"  width="100px">     
  12.                                 @names.Text     
  13.                             </td>     
  14.                         </tr>     
  15.                     </table>      
  16. }     
  17. </div>  
In this code I am using a foreach loop, that helps me to take all the StudentNames List from my Model to names , which is a var type.
  1. @foreach (var names in @Model.StudentNames) 
Now I will generate my Checkbox Id and <td> id because I want to generate these ids dynamically.
  1. var checkBoxId = "chk" + names.Value;     
  2. var tdId = "td" + names.Value; 
Now I just create a simple HTML table and use a checkbox and in the table cell (td) I am passing names as a text value.
  1. <table width="100%">     
  2.     <tr >     
  3.         <td width="20px">     
  4.            <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />     
  5.        </td>     
  6.        <td id="@tdId"  width="100px">     
  7.            @names.Text     
  8.        </td>     
  9.    </tr>     
  10. </table>  
Now, using JQuery , when the user clicks a checkbox, it simply sets its table cell (td) background to blue.
  1. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  2. <script>     
  3.     $(document).ready(function () {  
  4.         $('.chkclass').click(function () {         
  5.             var getchkid = $(this).attr('id');     
  6.             var isChecked = $('#' + getchkid).is(':checked');     
  7.       
  8.             if ($('#' + getchkid).is(':checked') == true) {     
  9.                 $('#td' + $(this).val()).css("color""white");     
  10.                 $('#td' + $(this).val()).css("background-color""blue");     
  11.             }     
  12.             else {     
  13.                 $('#td' + $(this).val()).css("color""black");     
  14.                 $('#td' + $(this).val()).css("background-color""white");     
  15.             }     
  16.         });   
  17.     });  
  18. </script>  
Now the question arises, how will you send your selected values to controller, because once you get the values into controller, you can do anything like save into database. So let’s understand the below code.
  1. $('#bttn_Click').click(function () {    
  2.                 
  3.             var studentListVal = null;    
  4.             studentListVal = [];    
  5.                 
  6.             $('input:checkbox:checked').each(function () {    
  7.                 studentListVal.push($(this).attr('value'));    
  8.             });    
  9.     
  10.             $.ajax({    
  11.                 type: "post",    
  12.                 url: "/Student/Studentl",    
  13.                 data: { Name: studentListVal },    
  14.                 datatype: "json",    
  15.                 traditional: true,    
  16.                 success: function (data) {    
  17.                         
  18.                     var selectedIds;    
  19.                     for (var i = 0; i < data.success.length; i++)    
  20.                     {    
  21.                         if (selectedIds != undefined) {    
  22.                             selectedIds = selectedIds + " " + data.success[i];    
  23.                         }    
  24.                         else {    
  25.                             selectedIds = data.success[i];    
  26.                         }    
  27.                     }    
  28.                     alert('You have Selected Student Ids- '+selectedIds);    
  29.                 }    
  30.             });  
  31.         });  
In the above code, we have studentListVal this is array type, with the use of push command we fill all values of selected checkbox into that array.
  1. $('input:checkbox:checked').each(function () {    
  2.                 studentListVal.push($(this).attr('value'));    
  3.             });  
Now for sending value to controller, look at this Ajax code.
  1. $.ajax({    
  2.                 type: "post",    
  3.                 url: "/Student/Studentl",    
  4.                 data: { Name: studentListVal },    
  5.                 datatype: "json",    
  6.                 traditional: true,    
  7.                 success: function (data) {    
  8.                         
  9.                     var selectedIds;    
  10.                     for (var i = 0; i < data.success.length; i++)    
  11.                     {    
  12.                         if (selectedIds != undefined) {    
  13.                             selectedIds = selectedIds + " " + data.success[i];    
  14.                         }    
  15.                         else {    
  16.                             selectedIds = data.success[i];    
  17.                         }    
  18.                     }    
  19.                     alert('You have Selected Student Ids- '+selectedIds);    
  20.                 }    
  21.      });   
Now look at the below code at controller/
  1. [HttpPost]    
  2. public ActionResult Studentl(string[] Name)    
  3. {    
  4.    return Json(new { success = Name });    
  5. }  
cs code

That's it. I hope you enjoy to create this checkboxlist in MVC. If you have any query, Please send your valuable Comments. Happy Programming!


Similar Articles