Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / ASM
Tip/Trick

CheckBoxList in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
3.75/5 (3 votes)
10 Jan 2016CPOL3 min read 29.9K   5   2
This tip explains how to create a checkboxlist in MVC.

Introduction

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.

Image 1

So in this tip, I am going to explain how to create a checkboxlist in MVC and send its selected data to controller.

Please follow the steps given below.

Using the Code

Step 1

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

Image 2

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

Image 3

Step 4

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

Image 4

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

Now add the following code:

JavaScript
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 an "IList<SelectListItem>" type property. This SelectListItem returns both text and a value that is helpful for lists (like Dropdownlist, Listbox, etc.).

We will now write the code for a Controller.

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

Image 5

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

JavaScript
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
    {
        //
        // GET: /Student/

        public ActionResult Index()
        {
            return View();
        }

        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" });
            objStudentModel.StudentNames = names;
            
            return View(objStudentModel);
        }

        [HttpPost]
        public ActionResult Studentl(string[] Name)
        {
            return Json(new { success = Name });
        }

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, etc.

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

Image 6

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

Student.cshtml

HTML
@model CheckboxListDemo.Models.StudentModel
@{
    ViewBag.Title = "Student";
}
 
<h2>Student</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");
            }
        });
 
        $('#bttn_Click').click(function () {
           
            var studentListVal = null;
            studentListVal = [];
           
            $('input:checkbox:checked').each(function () {
                studentListVal.push($(this).attr('value'));
            });
 
            $.ajax({
                type: "post",
                url: "/Student/Studentl",
                data: { Name: studentListVal },
                datatype: "json",
                traditional: true,
                success: function (data) {
                   
                    var selectedIds;
                    for (var i = 0; i < data.success.length; i++)
                    {
                        if (selectedIds != undefined) {
                            selectedIds = selectedIds + " " + data.success[i];
                        }
                        else {
                            selectedIds = data.success[i];
                        }
                    }
                    alert('You have Selected Student Ids- '+selectedIds);
                }
            }); 
        }); 
    });
 
</script>
 
<div id="divStudentlist" 
style="height: 100px; 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>
<div>
    <input type="button" id="bttn_Click" 
    value="Send Checked value to Controller" />
</div>

StudentController.cs

JavaScript
    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
    {
        //
        // GET: /Student/

        public ActionResult Index()
        {
            return View();
        }

        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" });
            objStudentModel.StudentNames = names;
            
            return View(objStudentModel);
        }

        [HttpPost]
        public ActionResult Studentl(string[] Name)
        {
            return Json(new { success = Name });
        }
</selectlistitem></selectlistitem>

Your view is now created and you are ready to run your CheckboxList Program. So Press F5 and run your code.

Image 7

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:

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

JavaScript
@foreach (var names in @Model.StudentNames)

Now, I will generate my Checkbox Id and <td> id because I want to generate these ids dynamically.

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

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

HTML
<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>

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.

JavaScript
$('#bttn_Click').click(function () {

        var studentListVal = null;
        studentListVal = [];

        $('input:checkbox:checked').each(function () {
            studentListVal.push($(this).attr('value'));
        });

        $.ajax({
            type: "post",
            url: "/Student/Studentl",
            data: { Name: studentListVal },
            datatype: "json",
            traditional: true,
            success: function (data) {

                var selectedIds;
                for (var i = 0; i < data.success.length; i++)
                {
                    if (selectedIds != undefined) {
                        selectedIds = selectedIds + " " + data.success[i];
                    }
                    else {
                        selectedIds = data.success[i];
                    }
                }
                alert('You have Selected Student Ids- '+selectedIds);
            }
        });
    });

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.

JavaScript
$('input:checkbox:checked').each(function () {
            studentListVal.push($(this).attr('value'));
        });

Now for sending value to controller, look at this Ajax code.

JavaScript
$.ajax({
            type: "post",
            url: "/Student/Studentl",
            data: { Name: studentListVal },
            datatype: "json",
            traditional: true,
            success: function (data) {

                var selectedIds;
                for (var i = 0; i < data.success.length; i++)
                {
                    if (selectedIds != undefined) {
                        selectedIds = selectedIds + " " + data.success[i];
                    }
                    else {
                        selectedIds = data.success[i];
                    }
                }
                alert('You have Selected Student Ids- '+selectedIds);
            }
        });

Now look at the below code at controller:

JavaScript
[HttpPost]
    public ActionResult Studentl(string[] Name)
    {
        return Json(new { success = Name });
    }

Image 8

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralNice one Pin
Member 1338498229-Aug-17 21:06
Member 1338498229-Aug-17 21:06 
GeneralRe: Nice one Pin
Member 1202181712-Nov-17 18:44
Member 1202181712-Nov-17 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.