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:
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)
Step 3
Embed the following CSS and JS into your project:
- bootstrap-multiselect.css
- bootstrap-multiselect.js
Step 4
Create a MainController.cs in which creates an index method for listing all teachers:
public IActionResult Index()
{
var teacherList = db.Teacher.ToList();
return View(teacherList);
}
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
@model List<Teacher>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Teacher's List</h1>
<a href="Main/AddTeacher" class="btn btn-primary">Add Teacher <i class="fa fa-plus"></i></a>
<table class="table table-bordered">
<thead>
<tr><td>Name</td><td>Action</td></tr>
</thead>
<tbody>
@if (Model.Count > 0)
{
foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td><a href="Main/AddTeacher/@item.Id" class="btn btn-warning">Edit Teacher <i class="fa fa-edit"></i></a></td>
</tr>
}
}
</tbody>
</table>
Step 6
Now let's create a method for adding teacher into the database
public IActionResult AddTeacher(long? Id)
{
TeacherDto model = new TeacherDto(); List<long> subjectsIds = new List<long>();
if (Id.HasValue)
{
//Get teacher
var teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == Id.Value);
//Get teacher subjects and add each subjectId into subjectsIds list
teacher.TeacherSubjects.ToList().ForEach(result => subjectsIds.Add(result.SubjectId));
//bind model
model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
model.Id = teacher.Id;
model.Name = teacher.Name;
model.SubjectsIds = subjectsIds.ToArray();
}
else
{
model = new TeacherDto();
model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
}
return View(model);
}
TeacherDto.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MulticheckboxDropdown.Models
{
public class TeacherDto
{
public long Id { get; set; }
public string Name { get; set; }
public List<SelectListItem> drpSubjects { get; set; }
[Display(Name="Subjects")]
public long[] SubjectsIds { get; set; }
}
}
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.
public IActionResult AddTeacher(TeacherDto model)
{
Teacher teacher = new Teacher();
List<TeacherSubjects> teacherSubjects = new List<TeacherSubjects>();
if (model.Id > 0)
{
//first find teacher subjects list and then remove all from db
teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == model.Id);
teacher.TeacherSubjects.ToList().ForEach(result => teacherSubjects.Add(result));
db.TeacherSubjects.RemoveRange(teacherSubjects);
db.SaveChanges();
//Now update teacher details
teacher.Name = model.Name;
if (model.SubjectsIds.Length > 0)
{
teacherSubjects = new List<TeacherSubjects>();
foreach (var subjectid in model.SubjectsIds)
{
teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });
}
teacher.TeacherSubjects = teacherSubjects;
}
db.SaveChanges();
}
else
{
teacher.Name = model.Name;
teacher.DateTimeInLocalTime = DateTime.Now;
teacher.DateTimeInUtc = DateTime.UtcNow;
if (model.SubjectsIds.Length > 0)
{
foreach (var subjectid in model.SubjectsIds)
{
teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });
}
teacher.TeacherSubjects = teacherSubjects;
}
db.Teacher.Add(teacher);
db.SaveChanges();
}
return RedirectToAction("index");
}
Step 8
Here is the complete MainController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using MulticheckboxDropdown.Database;
using MulticheckboxDropdown.Models;
using Microsoft.EntityFrameworkCore;
namespace MulticheckboxDropdown.Controllers
{
public class MainController : Controller
{
private readonly ApplicationDbContext db;
public MainController(ApplicationDbContext db)
{
this.db = db;
}
public IActionResult Index()
{
var teacherList = db.Teacher.ToList();
return View(teacherList);
}
public IActionResult AddTeacher(long? Id)
{
TeacherDto model = new TeacherDto(); List<long> subjectsIds = new List<long>();
if (Id.HasValue)
{
//Get teacher
var teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == Id.Value);
//Get teacher subjects and add each subjectId into subjectsIds list
teacher.TeacherSubjects.ToList().ForEach(result => subjectsIds.Add(result.SubjectId));
//bind model
model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
model.Id = teacher.Id;
model.Name = teacher.Name;
model.SubjectsIds = subjectsIds.ToArray();
}
else
{
model = new TeacherDto();
model.drpSubjects = db.Subjects.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
}
return View(model);
}
[HttpPost]
public IActionResult AddTeacher(TeacherDto model)
{
Teacher teacher = new Teacher();
List<TeacherSubjects> teacherSubjects = new List<TeacherSubjects>();
if (model.Id > 0)
{
//first find teacher subjects list and then remove all from db
teacher = db.Teacher.Include("TeacherSubjects").FirstOrDefault(x => x.Id == model.Id);
teacher.TeacherSubjects.ToList().ForEach(result => teacherSubjects.Add(result));
db.TeacherSubjects.RemoveRange(teacherSubjects);
db.SaveChanges();
//Now update teacher details
teacher.Name = model.Name;
if (model.SubjectsIds.Length > 0)
{
teacherSubjects = new List<TeacherSubjects>();
foreach (var subjectid in model.SubjectsIds)
{
teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });
}
teacher.TeacherSubjects = teacherSubjects;
}
db.SaveChanges();
}
else
{
teacher.Name = model.Name;
teacher.DateTimeInLocalTime = DateTime.Now;
teacher.DateTimeInUtc = DateTime.UtcNow;
if (model.SubjectsIds.Length > 0)
{
foreach (var subjectid in model.SubjectsIds)
{
teacherSubjects.Add(new TeacherSubjects { SubjectId = subjectid, TeacherId = model.Id });
}
teacher.TeacherSubjects = teacherSubjects;
}
db.Teacher.Add(teacher);
db.SaveChanges();
}
return RedirectToAction("index");
}
}
}
Step 9
Create a AddTeacher.cshtml view:
@model TeacherDto
@{
ViewData["Title"] = "AddTeacher";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1> @(Model.Id>0?"Edit Teacher": "Add Teacher")</h1>
<div class="container-fluid">
<form method="post" asp-action="AddTeacher" asp-controller="Main">
<div class="form-group row">
@Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, new { @class = "col-sm-2 col-form-label" })
<div class="col-sm-6">
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "Enter Name" })
</div>
</div>
<div class="form-group row">
@Html.LabelFor(model => model.SubjectsIds, new { @class = "col-sm-2 col-form-label" })
<div class="col-sm-6">
@Html.ListBoxFor(model => model.SubjectsIds,new MultiSelectList(Model.drpSubjects, "Value", "Text"), new { @class = "form-control", multiple = "multiple", id = "Subjects_dropdown" })
</div>
</div>
<div class="form-group row">
<input type="submit" name="name" value="@(Model.Id>0?"Update": "Add")" class="btn btn-success" />
</div>
</form>
</div>
@section Scripts{
<script>
$(document).ready(function () {
$('#Subjects_dropdown').multiselect();
});
</script>
}
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.
Here is the Add Teacher view for adding a teacher:
And the Edit teacher View:
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.