Multi-Select Dropdown With Checkboxes Using jQuery In MVC

Introduction

 
This article is about creating a multi-select dropdown with checkboxes in MVC by using Jquery on Countries sample data. This kind of scenario is used on applications such as on insurance domain. When a customer needed to be provided with travel or health Insurance from the origin to the destination country or if the person is traveling to multiple destinations. 
 
Here, I’ll try to explain the process involved in creating MultiSelect Dropdown with checkboxes.
 
To understand, knowledge of SQL, MVC, EntityFramework, LINQ, and Jquery is needed.
 

Steps in Creating the Application

  1. Create an SQL Database with Table using the mentioned Dbscript.
  2. Using Visual Studio Create an MVC Web Application
  3. To the Models Folder, Add ADO.NET Entity Data Model by selecting Database First Approach with appropriate connections select the database and table for creating the edmx file.
  4. Add a Controller with the required action method needed for this scenario.
  5. Generate a View for Create Action Method or Just create the View manually and Add the code to it.
  6. Add required script files in the View, which are needed for MultiSelect Dropdown so that the checkboxes will be shown along with the Dropdown.
  7. If there is any trouble in creating Views or the data is shown irrelevant on the screen, just rebuild the solution and re-run the application.

Creating an SQL Database

 
We create a Database named as MultiselectDropdown with a Table CountriesList and Insert the countries list into it.
  1. CREATE DATABASE [MultiselectDropdown]    
  2. Go    
  3. USE [MultiselectDropdown]    
  4. CREATE TABLE [dbo].[CountriesList](    
  5. [Id] int Identity(1,1)    NOT NULL,    
  6. [Country_Code] varchar(2) NOT NULL,    
  7. [DestinationCountry] nvarchar(100) NOT NULL,     
  8. PRIMARY KEY (Id)    
  9. )    
  10. INSERT INTO [dbo].[CountriesList] VALUES ( 'AF''Afghanistan');    
  11. INSERT INTO [dbo].[CountriesList] VALUES ( 'AL''Albania');    

  12. INSERT INTO [dbo].[CountriesList] VALUES ( 'DZ''Algeria');    
  13. INSERT INTO [dbo].[CountriesList] VALUES ( 'DS''American Samoa');    
  14. INSERT INTO [dbo].[CountriesList] VALUES ( 'AD''Andorra');    
  15. INSERT INTO [dbo].[CountriesList] VALUES ( 'AO''Angola');    
  16. INSERT INTO [dbo].[CountriesList] VALUES ( 'AI''Anguilla');    
  17. INSERT INTO [dbo].[CountriesList] VALUES ( 'AQ''Antarctica');    
  18. INSERT INTO [dbo].[CountriesList] VALUES ( 'AG''Antigua and Barbuda');    
  19. INSERT INTO [dbo].[CountriesList] VALUES ( 'AR''Argentina');   
Creating an Edmx File with the help of ADO.NET Entity Data Model
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
Adding a Controller and Creating an Action Method
  1. using System.Linq;  
  2. using System.Web.Mvc;  
  3. using MultiSelectDropdown.Models;  
  4.   
  5. namespace MultiSelectDropdown.Controllers  
  6. {  
  7.     public class InsuranceCertificateController : Controller  
  8.     {   
  9.         public ActionResult Index()  
  10.         {  
  11.             return View();  
  12.         }  
  13.   
  14.         [HttpGet]  
  15.         public ActionResult Create()  
  16.         {  
  17.             using (MultiselectDropdownEntities db = new MultiselectDropdownEntities())  
  18.             {  
  19.                 var result = (from CountriesList in db.CountriesLists select CountriesList).ToList();  
  20.                 if(result!=null)  
  21.                 {  
  22.                     ViewBag.myCountries = result.Select(x => new SelectListItem { Text = x.DestinationCountry, Value = x.Id.ToString() });  
  23.                 }                   
  24.             }  
  25.             return View();  
  26.         } 
  27.     }  
  28. }  

Adding View

 
Right-click on "Create" Action Method,  select Add View and name it as "Create" and add the required code which is needed for MultiSelect Dropdown with Checkboxes.
  1. @model MultiSelectDropdown.Models.InsuranceCertificate  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm()  
  10.                         {  
  11.             @Html.AntiForgeryToken()  
  12.   
  13.             <div class="form-horizontal">  
  14.     <h4>InsuranceCertificate</h4>  
  15.     <hr />  
  16.   
  17.     <div class="form-group">  
  18.         @Html.LabelFor(model => model.DestinationCountry, htmlAttributes: new { @class = "control-label col-md-2" })  
  19.         <div class="col-md-10">  
  20.   
  21.             <input type="button" id="btnmyCountries" value="Get Selected Countries" />  /*id="btnmyCountries" is taken from JQuery Click Function which is written at the end of this View*/  
  22.   
  23.             <div>  
  24.                 <select id="myCountries" multiple="multiple" required=required name="myCountries"> /*id = "myCountries" is taken from JQuery Function multiselect which is written at the end of this View*/  
  25.                     @if (ViewBag.myCountries != null)   @*ViewBag.myCountries is taken from Controller Create Action Method*@  
  26.                     {  
  27.                         foreach (var item in ViewBag.myCountries)  
  28.                         {  
  29.                             if (item.Text != null)  
  30.                             {  
  31.                                 <option value="@item.Value">  
  32.                                     @item.Text  
  33.                                 </option>  
  34.                             }  
  35.                         }  
  36.                     }  
  37.                 </select>  
  38.             </div>  
  39.         </div>  
  40.     </div>  
  41.   
  42.     <div class="form-group">  
  43.         <div class="col-md-offset-2 col-md-10">  
  44.             <input type="submit" value="Create" class="btn btn-default" />  
  45.         </div>  
  46.     </div>  
  47. </div>  
  48. }  
  49.   
  50. <div>  
  51.     @Html.ActionLink("Back to List""Index")  
  52. </div>  
  53.   
  54. @section Scripts {  
  55.     @Scripts.Render("~/bundles/jqueryval")  
  56.     <head runat="server">  
  57.         <script src="~/Scripts/jquery-3.3.1.min.js"></script>  
  58.         <script src="~/Scripts/bootstrap.js"></script>  
  59.         <script src="~/Scripts/bootstrap.min.js"></script>  
  60.         <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  61.         <script src="~/Scripts/bootstrap-multiselect.js"></script>  
  62.         <link href="~/Content/bootstrap-multiselect.css" rel="stylesheet" />  
  63.         <script type="text/javascript">  
  64.   
  65.   
  66.         $(function () {  
  67.             $('#myCountries').multiselect({  
  68.                 includeSelectAllOption: true,         /*To enable the Select all Option*/  
  69.                 selectAllValue: 'multiselect-all',     /*The value used for the select all option can be configured using the selectAllValue*/
  70.                 enableFiltering: true,   /*A filter input will be added to dynamically filter all the options*/  
  71.                 enableCaseInsensitiveFiltering: true,  /*To enable Case Insenstitive Filtering (Upper and Lower Case Letters)*/  
  72.                 maxHeight: '300',  
  73.                 buttonWidth: '235',  
  74.             });  
  75.         });  
  76.   
  77.         $("#btnmyCountries").click(function () {  
  78.             var selected = $("#myCountries option:selected");    /*Current Selected Value*/  
  79.             var message = "";  
  80.             var arrSelected = [];      /*Array to store multiple values in stack*/  
  81.             selected.each(function () {  
  82.                 arrSelected.push($(this).val());    /*Stack the Value*/  
  83.                 message += $(this).text() + " " + $(this).val() + "\n";  
  84.             });  
  85.             alert(message);  
  86.             });  
  87.         </script>  
  88.     </head>  

Adding required Script files to the view

 
It is mandatory to add script files to the "Create" View and files like jquery-3.3.1.min.js, bootstrap.js, bootstrap.min.js, bootstrap.min.css are added by default while creating a project by selecting a Project Template as an MVC Project. The remaining files like bootstrap-multiselect.js, bootstrap-multiselect.css, to be downloaded and added to the project and include a reference in the View. Without these two files, we get the output without checkboxes like below,
 
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
 
The multi-select bootstrap files are taken from this link where bootstrap-multiselect.js is available in dist -> js and bootstrap-multiselect.css is available in dist -> css folders. By adding these two files to the project and reference to the View, we can achieve the intended output like below.
 
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
In the output "Get Selected Countries" is the button to retrieve the selected countries, after selecting the countries if we click on the button we get the output as shown below.
 
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
 
Note
If you are not using "multiple" attribute in the View inside <select id="myCountries"multiple="multiple"required=required name="myCountries"> You'll get the output as Radio button like below.
 
Always be sure to include the "multiple" attribute with the "select" so that we get the output with Checkboxes.  
 
MultiSelect Dropdown With Checkboxes Using jQuery In MVC
 
You can do various workarounds by following the instructions on this link with the help of bootstrap-multiselect.
 

Conclusion

 
In this article, we learned to get the details from the database and to populate the Countries data on Dropdown MultiSelect-Checkboxes by using the Create Action Method with the help of Linq and the View which is coded using JQuery with the help of multi-select bootstrap.
 
Happy Coding!


Similar Articles