Reader Level:
Articles

CheckBoxList in ASP.NET MVC 4

By Sourabh Mishra on May 25, 2013
This article explains how to create a checkboxlist in MVC.
  • 1
  • 0
  • 63430

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.          
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18. //  
  19.         // GET: /Student/  
  20.    
  21.    
  22.         public ActionResult Student()  
  23.         {  
  24.             StudentModel objStudentModel = new StudentModel();  
  25.    
  26.             List<SelectListItem> names = new List<SelectListItem>();  
  27.             names.Add(new SelectListItem { Text = "Sourabh", Value = "1" });  
  28.             names.Add(new SelectListItem { Text = "Surbhee", Value = "2" });  
  29.             names.Add(new SelectListItem { Text = "Vinay", Value = "3" });  
  30.             names.Add(new SelectListItem { Text = "Tushar", Value = "4" });  
  31.      names.Add(new SelectListItem { Text = "John", Value = "5" });  
  32.             names.Add(new SelectListItem { Text = "Tom", Value = "6" });  
  33.             objStudentModel.StudentNames = names;  
  34.              
  35.             return View(objStudentModel);  
  36.         }  
  37.    
  38.     }  
  39. }  

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.   
  6. <h2>Student</h2>  
  7.   
  8. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  9.   
  10. <script>  
  11.     $(document).ready(function () {  
  12.         $('.chkclass').click(function () {  
  13.               
  14.             var getchkid = $(this).attr('id');  
  15.             var isChecked = $('#' + getchkid).is(':checked');  
  16.   
  17.             if ($('#' + getchkid).is(':checked') == true) {  
  18.                 $('#td' + $(this).val()).css("color""white");  
  19.                 $('#td' + $(this).val()).css("background-color""blue");  
  20.             }  
  21.             else {  
  22.                 $('#td' + $(this).val()).css("color""black");  
  23.                 $('#td' + $(this).val()).css("background-color""white");  
  24.             }  
  25.         });  
  26.   
  27.         $('#bttn_Click').click(function () {  
  28.               
  29.             var studentListVal = null;  
  30.             studentListVal = [];  
  31.               
  32.             $('input:checkbox:checked').each(function () {  
  33.                 studentListVal.push($(this).attr('value'));  
  34.             });  
  35.   
  36.             $.ajax({  
  37.                 type: "post",  
  38.                 url: "/Student/Studentl",  
  39.                 data: { Name: studentListVal },  
  40.                 datatype: "json",  
  41.                 traditional: true,  
  42.                 success: function (data) {  
  43.                       
  44.                     var selectedIds;  
  45.                     for (var i = 0; i < data.success.length; i++)  
  46.                     {  
  47.                         if (selectedIds != undefined) {  
  48.                             selectedIds = selectedIds + " " + data.success[i];  
  49.                         }  
  50.                         else {  
  51.                             selectedIds = data.success[i];  
  52.                         }  
  53.                     }  
  54.                     alert('You have Selected Student Ids- '+selectedIds);  
  55.                 }  
  56.             });  
  57.   
  58.         });  
  59.   
  60.     });  
  61.   
  62. </script>  
  63.   
  64. <div id="divStudentlist" style="height: 100px; overflow: auto;border:solid; width:150px;">  
  65. @foreach (var names in @Model.StudentNames)  
  66. {  
  67.     var checkBoxId = "chk" + names.Value;  
  68.     var tdId = "td" + names.Value;  
  69.                     <table width="100%">  
  70.                         <tr >  
  71.                             <td width="20px">  
  72.                                 <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />  
  73.                             </td>  
  74.                             <td id="@tdId"  width="100px">  
  75.                                 @names.Text  
  76.                             </td>  
  77.                         </tr>  
  78.                          
  79.                     </table>  
  80.   
  81. }  
  82.     </div>  
  83.   
  84. <div>  
  85.     <input type="button" id="bttn_Click" value="Send Checked value to Controller" />  
  86. </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.         }  
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. }   
  18.     </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. lt;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. lt;/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.     
  3. <script>   
  4.     $(document).ready(function () {   
  5.           
  6.     
  7.         $('.chkclass').click(function () {   
  8.               
  9.             var getchkid = $(this).attr('id');   
  10.             var isChecked = $('#' + getchkid).is(':checked');   
  11.     
  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.     
  22.     });   
  23.     
  24. </script>  
Now the question arises, how will you send your selected values to controller, because once you get the values in to 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.   
  32.         });  
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.

Sourabh Mishra

Sourabh Mishra is an IT geek, Developer, Trainer and Animator. He is a Microsoft guy, He is very passionate about Microsoft technologies. He is always ready to learn new technologies. currently serving a MNC as a Develop... Read more

COMMENT USING

Trending up