CheckBoxList in ASP.NET MVC4

Sourabh_Mishra1
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 4374 red flag

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.

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.

    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...".

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".

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".

Figure 3: Add a New model.

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

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
  
namespace CheckboxListDemo.Models 
{ 
    public class StudentModel 
    { 
      public IList<SelectListItem> StudentNames { get; set; } 
    } 
} 
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".


Figure 4: Add New Controller

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

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CheckboxListDemo.Models; namespace CheckboxListDemo.Controllers { public class StudentController : Controller { public ActionResult Index() { return View(); } // // GET: /Student/ public ActionResult Student() { StudentModel objStudentModel = new StudentModel(); List<SelectListItem> names = new List<SelectListItem>(); names.Add(new SelectListItem { Text = "Sourabh", Value = "1" }); names.Add(new SelectListItem { Text = "Surbhee", Value = "2" }); names.Add(new SelectListItem { Text = "Vinay", Value = "3" }); names.Add(new SelectListItem { Text = "Tushar", Value = "4" }); names.Add(new SelectListItem { Text = "John", Value = "5" }); names.Add(new SelectListItem { Text = "Tom", Value = "6" }); objStudentModel.StudentNames = names; return View(objStudentModel); } } }


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".

Figure 5: Add View

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

@model CheckboxListDemo.Models.StudentModel 
@{ 
    ViewBag.Title = "Student"; 
    Layout = null; 
} 
  
<h2>Students List</h2> 
  
<script src="~/Scripts/jquery-1.7.1.min.js"></script> 
  
<script> 
    $(document).ready(function () { 
        
  
        $('.chkclass').click(function () { 
            
            var getchkid = $(this).attr('id'); 
            var isChecked = $('#' + getchkid).is(':checked'); 
  
            if ($('#' + getchkid).is(':checked') == true) { 
                $('#td' + $(this).val()).css("color", "white"); 
                $('#td' + $(this).val()).css("background-color", "blue"); 
            } 
            else { 
                $('#td' + $(this).val()).css("color", "black"); 
                $('#td' + $(this).val()).css("background-color", "white"); 
            } 
        }); 
  
    }); 
  
</script> 
  
  
<div id="divstudentlist" class="elem" style="height: 110px; overflow: auto;border:solid; width:150px;"> 
@foreach (var names in @Model.StudentNames) 
{ 
    var checkBoxId = "chk" + names.Value; 
    var tdId = "td" + names.Value; 
                    <table width="100%"> 
                        <tr > 
                            <td width="20px"> 
                                <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" /> 
                            </td> 
                            <td id="@tdId"  width="100px"> 
                                @names.Text 
                            </td> 
                        </tr> 
                    </table> 
  
} 
    </div> 
Your view is now created and you are ready to run your CheckboxList Program. So Press F5 and run your code. 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:

<div id="divstudentlist" style="height: 110px; overflow: auto;border:solid; width:150px;"> 
@foreach (var names in @Model.StudentNames) 
{ 
    var checkBoxId = "chk" + names.Value; 
    var tdId = "td" + names.Value; 
                    <table width="100%"> 
                        <tr > 
                            <td width="20px"> 
                                <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" /> 
                            </td> 
                            <td id="@tdId"  width="100px"> 
                                @names.Text 
                            </td> 
                        </tr> 
                    </table> 
  
} 
    </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.

@foreach (var names in @Model.StudentNames)

Now I will generate my Checkbox Id and <td> id because I want to generate these ids dynamically.
  
var checkBoxId = "chk" + names.Value;  
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. 

<table width="100%"> 
     <tr > 
         <td width="20px"> 
<input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" /> 
        </td> 
        <td id="@tdId"  width="100px"> 
            @names.Text 
        </td> 
    </tr> 
</table> 

Now, using jQuery , when the user clicks a checkbox, it simply sets its table cell (td) background to blue.
  
<script src="~/Scripts/jquery-1.7.1.min.js"></script> 
  
<script> 
    $(document).ready(function () { 
        
  
        $('.chkclass').click(function () { 
            
            var getchkid = $(this).attr('id'); 
            var isChecked = $('#' + getchkid).is(':checked'); 
  
            if ($('#' + getchkid).is(':checked') == true) { 
                $('#td' + $(this).val()).css("color", "white"); 
                $('#td' + $(this).val()).css("background-color", "blue"); 
            } 
            else { 
                $('#td' + $(this).val()).css("color", "black"); 
                $('#td' + $(this).val()).css("background-color", "white"); 
            } 
        }); 
  
    }); 
  
</script>


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

Page copy protected against web site content infringement by Copyscape

About the Author

Sourabh_Mishra1
Full Name: sourabh mishra
Member Level: Starter
Member Status: Member
Member Since: 2/11/2013 1:20:00 PM
Country: India
Sourabh Mishra
http://www.dotnetfunda.com
I am a .Net Developer my skills are asp.net,c#, sqlserver,wcf,jquery. My mail id is sourabh_mishra1@hotmail.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)