Multi-Select Checkbox Dropdown List - Create And Edit In .NET Core 3.1

Introduction

 
In this article, I will explain how to create a multi-checkbox dropdown list in ASP.NET Core 3.1 MVC. I am going to create a multi-select checkbox dropdown list with the help of "bootstrap-multiselect" CSS and JS. Also, we will see how to edit this dropdown list with database data. Along with this, I'll show you how you maintain a database for this type of data and display a list of data.
 

Overview

 
Here, I am going to create a teacher example, where I create a teacher with their name and multiple subjects and save them into the database, display the teacher list and edit each teacher with their subject list.
 
We are creating a dropdown list that looks like this:
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
Let's see how to create this:
 
Step 1
 
Create a .NET Core 3.1 web application
 
Step 2
 
Prepare the database for this holding this type of data, create 3 tables.
 
Table 1 - Teacher( holds teacher information)
 
Table 2-Subjects (holds all subjects)
 
Table 3-TeacherSubjects (holds teacher selected subject)
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Step 3
 
Embed the following CSS and JS into your project:
  • bootstrap-multiselect.css 
  • bootstrap-multiselect.js
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Step 4
 
Create a MainController.cs in which creates an index method for listing all teachers:
  1. public IActionResult Index()  
  2. {  
  3.     var teacherList = db.Teacher.ToList();  
  4.     return View(teacherList);  
  5. }  
Step 5
 
Now create an index.cshtml view for displaying all teachers list. Here, I create an additional link button for adding a teacher and render an edit link with each teacher.
 
index.cshtml view
  1. @model List<Teacher>  
  2. @{  
  3.     ViewData["Title"] = "Index";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6.   
  7. <h1>Teacher's List</h1>  
  8. <a href="Main/AddTeacher" class="btn btn-primary">Add Teacher <i class="fa fa-plus"></i></a>  
  9.   
  10. <table class="table table-bordered">  
  11.     <thead>  
  12.         <tr><td>Name</td><td>Action</td></tr>  
  13.     </thead>  
  14.     <tbody>  
  15.         @if (Model.Count > 0)  
  16.         {  
  17.             foreach (var item in Model)  
  18.             {  
  19.                 <tr>  
  20.                     <td>@item.Name</td>  
  21.                     <td><a href="Main/AddTeacher/@item.Id" class="btn btn-warning">Edit Teacher <i class="fa fa-edit"></i></a></td>  
  22.                 </tr>  
  23.   
  24.             }  
  25.         }  
  26.   
  27.     </tbody>  
  28. </table>  
Step 6
 
Now let's create a method for adding teacher into the database
  1. public IActionResult AddTeacher(long? Id)  
  2. {  
  3.     TeacherDto model = new TeacherDto(); List<long> subjectsIds = new List<long>();  
  4.     if (Id.HasValue)  
  5.     {  
  6.         //Get teacher   
  7.         var teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == Id.Value);  
  8.         //Get teacher subjects and add each subjectId into subjectsIds list  
  9.         teacher.TeacherSubjects.ToList().ForEach(result => subjectsIds.Add(result.SubjectId));  
  10.   
  11.         //bind model   
  12.         model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();  
  13.         model.Id = teacher.Id;  
  14.         model.Name = teacher.Name;  
  15.         model.SubjectsIds = subjectsIds.ToArray();  
  16.     }  
  17.     else  
  18.     {  
  19.         model = new TeacherDto();  
  20.         model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();  
  21.     }  
  22.   
  23.     return View(model);
  24. }
TeacherDto.cs
  1. using Microsoft.AspNetCore.Mvc.Rendering;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace MulticheckboxDropdown.Models  
  9. {  
  10.     public class TeacherDto  
  11.     {  
  12.         public long Id { getset; }  
  13.         public string Name { getset; }  
  14.         public List<SelectListItem> drpSubjects { getset; }  
  15.   
  16.         [Display(Name="Subjects")]  
  17.         public long[] SubjectsIds { getset; }  
  18.     }  
  19. }  
Above, we first find the Id's teacher, and because we have a foreign key relationship with TeacherSubjects Table, for accessing that teacher's Subjects list we have to include that table using LINQ Include ("TeacherSubjects") method. Then add each subject id into the long type List name subjectsIds, and pass this subjectsIds into the model by casting it with ToArray().
 
Step 7
 
Now create a HttpPost method for submitting and updating teachers with the database.
  1. public IActionResult AddTeacher(TeacherDto model)  
  2. {
  3.     Teacher teacher = new Teacher();  
  4.     List<TeacherSubjects> teacherSubjects = new List<TeacherSubjects>();  
  5.   
  6.   
  7.     if (model.Id > 0)  
  8.     {  
  9.         //first find teacher subjects list and then remove all from db   
  10.         teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == model.Id);  
  11.         teacher.TeacherSubjects.ToList().ForEach(result => teacherSubjects.Add(result));  
  12.         db.TeacherSubjects.RemoveRange(teacherSubjects);  
  13.         db.SaveChanges();  
  14.   
  15.         //Now update teacher details  
  16.         teacher.Name = model.Name;  
  17.         if (model.SubjectsIds.Length > 0)  
  18.         {  
  19.             teacherSubjects = new List<TeacherSubjects>();  
  20.   
  21.             foreach (var subjectid in model.SubjectsIds)  
  22.             {  
  23.                 teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });  
  24.             }  
  25.             teacher.TeacherSubjects = teacherSubjects;  
  26.         }  
  27.         db.SaveChanges();  
  28.   
  29.     }  
  30.     else  
  31.     {  
  32.         teacher.Name = model.Name;  
  33.         teacher.DateTimeInLocalTime = DateTime.Now;  
  34.         teacher.DateTimeInUtc = DateTime.UtcNow;  
  35.         if (model.SubjectsIds.Length > 0)  
  36.         {  
  37.             foreach (var subjectid in model.SubjectsIds)  
  38.             {  
  39.                 teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });  
  40.             }  
  41.             teacher.TeacherSubjects = teacherSubjects;  
  42.         }  
  43.         db.Teacher.Add(teacher);  
  44.         db.SaveChanges();  
  45.     }  
  46.     return RedirectToAction("index");  
  47. }  
Step 8
 
Here is the complete MainController.cs: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.AspNetCore.Mvc.Rendering;  
  7. using MulticheckboxDropdown.Database;  
  8. using MulticheckboxDropdown.Models;  
  9.   
  10. using Microsoft.EntityFrameworkCore;  
  11.   
  12.   
  13. namespace MulticheckboxDropdown.Controllers  
  14. {  
  15.     public class MainController : Controller  
  16.     {  
  17.         private readonly ApplicationDbContext db;  
  18.         public MainController(ApplicationDbContext db)  
  19.         {  
  20.             this.db = db;  
  21.         }  
  22.         public IActionResult Index()  
  23.         {  
  24.             var teacherList = db.Teacher.ToList();  
  25.             return View(teacherList);  
  26.         }  
  27.   
  28.   
  29.         public IActionResult AddTeacher(long? Id)  
  30.         {  
  31.             TeacherDto model = new TeacherDto(); List<long> subjectsIds = new List<long>();  
  32.             if (Id.HasValue)  
  33.             {  
  34.                 //Get teacher   
  35.                 var teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == Id.Value);  
  36.                 //Get teacher subjects and add each subjectId into subjectsIds list  
  37.                 teacher.TeacherSubjects.ToList().ForEach(result => subjectsIds.Add(result.SubjectId));  
  38.   
  39.                 //bind model   
  40.                 model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();  
  41.                 model.Id = teacher.Id;  
  42.                 model.Name = teacher.Name;  
  43.                 model.SubjectsIds = subjectsIds.ToArray();  
  44.             }  
  45.             else  
  46.             {  
  47.                 model = new TeacherDto();  
  48.                 model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();  
  49.             }  
  50.   
  51.             return View(model);  
  52.         }  
  53.   
  54.         [HttpPost]  
  55.         public IActionResult AddTeacher(TeacherDto model)  
  56.         {  
  57.             Teacher teacher = new Teacher();  
  58.             List<TeacherSubjects> teacherSubjects = new List<TeacherSubjects>();  
  59.   
  60.   
  61.             if (model.Id > 0)  
  62.             {  
  63.                 //first find teacher subjects list and then remove all from db   
  64.                 teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == model.Id);  
  65.                 teacher.TeacherSubjects.ToList().ForEach(result => teacherSubjects.Add(result));  
  66.                 db.TeacherSubjects.RemoveRange(teacherSubjects);  
  67.                 db.SaveChanges();  
  68.   
  69.                 //Now update teacher details  
  70.                 teacher.Name = model.Name;  
  71.                 if (model.SubjectsIds.Length > 0)  
  72.                 {  
  73.                     teacherSubjects = new List<TeacherSubjects>();  
  74.   
  75.                     foreach (var subjectid in model.SubjectsIds)  
  76.                     {  
  77.                         teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });  
  78.                     }  
  79.                     teacher.TeacherSubjects = teacherSubjects;  
  80.                 }  
  81.                 db.SaveChanges();  
  82.   
  83.             }  
  84.             else  
  85.             {  
  86.                 teacher.Name = model.Name;  
  87.                 teacher.DateTimeInLocalTime = DateTime.Now;  
  88.                 teacher.DateTimeInUtc = DateTime.UtcNow;  
  89.                 if (model.SubjectsIds.Length > 0)  
  90.                 {  
  91.                     foreach (var subjectid in model.SubjectsIds)  
  92.                     {  
  93.                         teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });  
  94.                     }  
  95.                     teacher.TeacherSubjects = teacherSubjects;  
  96.                 }  
  97.                 db.Teacher.Add(teacher);  
  98.                 db.SaveChanges();  
  99.             }  
  100.             return RedirectToAction("index");  
  101.         }  
  102.   
  103.     }  
  104. }  
Step 9
 
Create a AddTeacher.cshtml view:
  1. @model TeacherDto  
  2. @{  
  3.     ViewData["Title"] = "AddTeacher";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6.   
  7. <h1> @(Model.Id>0?"Edit Teacher""Add Teacher")</h1>  
  8. <div class="container-fluid">  
  9.     <form method="post" asp-action="AddTeacher" asp-controller="Main">  
  10.         <div class="form-group row">  
  11.             @Html.HiddenFor(model => model.Id)  
  12.             @Html.LabelFor(model => model.Name, new { @class = "col-sm-2 col-form-label" })  
  13.             <div class="col-sm-6">  
  14.                 @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "Enter Name" })  
  15.             </div>  
  16.         </div>  
  17.   
  18.         <div class="form-group row">  
  19.             @Html.LabelFor(model => model.SubjectsIds, new { @class = "col-sm-2 col-form-label" })  
  20.             <div class="col-sm-6">  
  21.                 @Html.ListBoxFor(model => model.SubjectsIds,new MultiSelectList(Model.drpSubjects, "Value""Text"), new { @class = "form-control", multiple = "multiple", id = "Subjects_dropdown" })  
  22.             </div>  
  23.         </div>  
  24.   
  25.   
  26.         <div class="form-group row">  
  27.             <input type="submit" name="name" value="@(Model.Id>0?"Update": "Add")" class="btn btn-success" />  
  28.         </div>  
  29.   
  30.     </form>  
  31. </div>  
  32. @section Scripts{  
  33.     <script>  
  34.         $(document).ready(function () {  
  35.             $('#Subjects_dropdown').multiselect();  
  36.         });  
  37.     </script>  
  38. }  
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
The "multiselect" is the method of bootstrap-multiselect.js which creates our dropdown list 
 
Output
 
On the index page, we are displaying all teacher's lists.
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
Here is the Add Teacher view for adding a teacher:
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1
And the Edit teacher View:
 
Multi Select Checkbox Dropdown List Create And Edit In .Net Core 3.1

Summary

 
In the above article, we learn to create and edit a multi-select checkbox dropdown list in ASP.NET Core 3.1 MVC, and adding a boostrap-multiselect CSS and JS for displaying the layout of this dropdown.