Multiple-selection is an important part of drop-down UI component as it improves the user interactivity with the website in order to allow the user to make his/her choice first and then send the request to the server for batch processing instead of again and again sending a request to the server for same choice selection. One of the cool things about the Bootstrap CSS framework is that it provides very rich and interactive built-in plugins which are easy to use and integrate with any server-side technology.

Today, I shall be demonstrating the integration of the Bootstrap CSS style drop-down with the enabling of multi-selection choice by using Bootstrap Select plugin into ASP.NET MVC5 platform.


Prerequisites

Following are some prerequisites before you proceed any further in this tutorial.

  1. Knowledge of ASP.NET MVC5.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of Jquery.
  6. Knowledge of C# Programming.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise. I am using Country table data extract from the Adventure Works Sample Database.

Let's begin now.

Step 1

Create a new MVC web project and name it "MultiSelectDropDown".

Step 2

Now, download the "Bootstrap Select" plug-in and place the respective JavaScript & CSS files into "Scripts" & "Content->style" folders.

Step 3

Open the "Views->Shared->_Layout.cshtml" file and replace following code in it.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>@ViewBag.Title</title>
  7. @Styles.Render("~/Content/css")
  8. @Scripts.Render("~/bundles/modernizr")
  9. <!-- Font Awesome -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
  11. </head>
  12. <body>
  13. <div class="navbar navbar-inverse navbar-fixed-top">
  14. <div class="container">
  15. <div class="navbar-header">
  16. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. </button>
  21. </div>
  22. </div>
  23. </div>
  24. <div class="container body-content">
  25. @RenderBody()
  26. <hr />
  27. <footer>
  28. <center>
  29. <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
  30. </center>
  31. </footer>
  32. </div>
  33. @*Scripts*@
  34. @Scripts.Render("~/bundles/jquery")
  35. @Scripts.Render("~/bundles/jqueryval")
  36. @Scripts.Render("~/bundles/bootstrap")
  37. @RenderSection("scripts", required: false)
  38. </body>
  39. </html>

In the above code, I have simply created a basic default layout page and linked the require libraries into it.

Step 4

Create a new "Helper_Code\Objects\CountryObj.cs" file and replace the following code in it.

  1. //-----------------------------------------------------------------------
  2. // <copyright file="CountryObj.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace SaveMultiSelectDropDown.Helper_Code.Objects
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Web;
  13. /// <summary>
  14. /// Country object class.
  15. /// </summary>
  16. public class CountryObj
  17. {
  18. #region Properties
  19. /// <summary>
  20. /// Gets or sets country ID property.
  21. /// </summary>
  22. public int Country_Id { get; set; }
  23. /// <summary>
  24. /// Gets or sets country name property.
  25. /// </summary>
  26. public string Country_Name { get; set; }
  27. #endregion
  28. }
  29. }

In the above code, I have simply created an object class which will map my sample list data in order to populate the drop-down list.

Step 5

Now, create another new "Models\MultiSelectDropDownViewModel.cs" file and replace the following code in it.

  1. //-----------------------------------------------------------------------
  2. // <copyright file="MultiSelectDropDownViewModel.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace SaveMultiSelectDropDown.Models
  8. {
  9. using System.Collections.Generic;
  10. using System.ComponentModel.DataAnnotations;
  11. using System.Web;
  12. using Helper_Code.Objects;
  13. /// <summary>
  14. /// Multi select drop down view model class.
  15. /// </summary>
  16. public class MultiSelectDropDownViewModel
  17. {
  18. #region Properties
  19. /// <summary>
  20. /// Gets or sets choose multiple countries property.
  21. /// </summary>
  22. [Required]
  23. [Display(Name = "Choose Multiple Countries")]
  24. public List<int> SelectedMultiCountryId { get; set; }
  25. /// <summary>
  26. /// Gets or sets selected countries property.
  27. /// </summary>
  28. public List<CountryObj> SelectedCountryLst { get; set; }
  29. #endregion
  30. }
  31. }

In the above code, I have created my view model which I will attach with my view. Here, I have created integer type list property which will capture my multiple selection values from the Razor View drop-down control and country object type list property which will display my multiple-selection choice in a table after processing on the server via ASP.NET MVC5 platform.

Step 6

Create a new "Controllers\MultiSelectDropDownController.cs" file and replace the following code in it.

  1. //-----------------------------------------------------------------------
  2. // <copyright file="MultiSelectDropDownController.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace SaveMultiSelectDropDown.Controllers
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Web;
  15. using System.Web.Mvc;
  16. using Helper_Code.Objects;
  17. using Models;
  18. /// <summary>
  19. /// Multi select drop down controller class.
  20. /// </summary>
  21. public class MultiSelectDropDownController : Controller
  22. {
  23. #region Index view method.
  24. #region Get: /MultiSelectDropDown/Index method.
  25. /// <summary>
  26. /// Get: /MultiSelectDropDown/Index method.
  27. /// </summary>
  28. /// <returns>Return index view</returns>
  29. public ActionResult Index()
  30. {
  31. // Initialization.
  32. MultiSelectDropDownViewModel model = new MultiSelectDropDownViewModel { SelectedMultiCountryId = new List<int>(), SelectedCountryLst = new List<CountryObj>() };
  33. try
  34. {
  35. // Loading drop down lists.
  36. this.ViewBag.CountryList = this.GetCountryList();
  37. }
  38. catch (Exception ex)
  39. {
  40. // Info
  41. Console.Write(ex);
  42. }
  43. // Info.
  44. return this.View(model);
  45. }
  46. #endregion
  47. #region POST: /MultiSelectDropDown/Index
  48. /// <summary>
  49. /// POST: /MultiSelectDropDown/Index
  50. /// </summary>
  51. /// <param name="model">Model parameter</param>
  52. /// <returns>Return - Response information</returns>
  53. [HttpPost]
  54. [AllowAnonymous]
  55. [ValidateAntiForgeryToken]
  56. public ActionResult Index(MultiSelectDropDownViewModel model)
  57. {
  58. // Initialization.
  59. string filePath = string.Empty;
  60. string fileContentType = string.Empty;
  61. try
  62. {
  63. // Verification
  64. if (ModelState.IsValid)
  65. {
  66. // Initialization.
  67. List<CountryObj> countryList = this.LoadData();
  68. // Selected countries list.
  69. model.SelectedCountryLst = countryList.Where(p => model.SelectedMultiCountryId.Contains(p.Country_Id)).Select(q => q).ToList();
  70. }
  71. // Loading drop down lists.
  72. this.ViewBag.CountryList = this.GetCountryList();
  73. }
  74. catch (Exception ex)
  75. {
  76. // Info
  77. Console.Write(ex);
  78. }
  79. // Info
  80. return this.View(model);
  81. }
  82. #endregion
  83. #endregion
  84. #region Helpers
  85. #region Load Data
  86. /// <summary>
  87. /// Load data method.
  88. /// </summary>
  89. /// <returns>Returns - Data</returns>
  90. private List<CountryObj> LoadData()
  91. {
  92. // Initialization.
  93. List<CountryObj> lst = new List<CountryObj>();
  94. try
  95. {
  96. // Initialization.
  97. string line = string.Empty;
  98. string rootFolderPath = this.Server.MapPath("~/Content/files/");
  99. string fileName = "country_list.txt";
  100. string fullPath = rootFolderPath + fileName;
  101. string srcFilePath = new Uri(fullPath).LocalPath;
  102. StreamReader sr = new StreamReader(new FileStream(srcFilePath, FileMode.Open, FileAccess.Read));
  103. // Read file.
  104. while ((line = sr.ReadLine()) != null)
  105. {
  106. // Initialization.
  107. CountryObj infoObj = new CountryObj();
  108. string[] info = line.Split(',');
  109. // Setting.
  110. infoObj.Country_Id = Convert.ToInt32(info[0].ToString());
  111. infoObj.Country_Name = info[1].ToString();
  112. // Adding.
  113. lst.Add(infoObj);
  114. }
  115. // Closing.
  116. sr.Dispose();
  117. sr.Close();
  118. }
  119. catch (Exception ex)
  120. {
  121. // info.
  122. Console.Write(ex);
  123. }
  124. // info.
  125. return lst;
  126. }
  127. #endregion
  128. #region Get country method.
  129. /// <summary>
  130. /// Get country method.
  131. /// </summary>
  132. /// <returns>Return country for drop down list.</returns>
  133. private IEnumerable<SelectListItem> GetCountryList()
  134. {
  135. // Initialization.
  136. SelectList lstobj = null;
  137. try
  138. {
  139. // Loading.
  140. var list = this.LoadData()
  141. .Select(p =>
  142. new SelectListItem
  143. {
  144. Value = p.Country_Id.ToString(),
  145. Text = p.Country_Name
  146. });
  147. // Setting.
  148. lstobj = new SelectList(list, "Value", "Text");
  149. }
  150. catch (Exception ex)
  151. {
  152. // Info
  153. throw ex;
  154. }
  155. // info.
  156. return lstobj;
  157. }
  158. #endregion
  159. #endregion
  160. }
  161. }

In the above code, I have created "LoadData(...)" and "GetCountryList(...)" helper methods which will help in country data loading from .txt file. I have also created GET & POST "Index(...)" methods for request & response purpose.

Let's break down each method and try to understand what have we added here. The first method that is created here is "LoadData()" method i.e.

  1. #region Load Data
  2. /// <summary>
  3. /// Load data method.
  4. /// </summary>
  5. /// <returns>Returns - Data</returns>
  6. private List<CountryObj> LoadData()
  7. {
  8. // Initialization.
  9. List<CountryObj> lst = new List<CountryObj>();
  10. try
  11. {
  12. // Initialization.
  13. string line = string.Empty;
  14. string rootFolderPath = this.Server.MapPath("~/Content/files/");
  15. string fileName = "country_list.txt";
  16. string fullPath = rootFolderPath + fileName;
  17. string srcFilePath = new Uri(fullPath).LocalPath;
  18. StreamReader sr = new StreamReader(new FileStream(srcFilePath, FileMode.Open, FileAccess.Read));
  19. // Read file.
  20. while ((line = sr.ReadLine()) != null)
  21. {
  22. // Initialization.
  23. CountryObj infoObj = new CountryObj();
  24. string[] info = line.Split(',');
  25. // Setting.
  26. infoObj.Country_Id = Convert.ToInt32(info[0].ToString());
  27. infoObj.Country_Name = info[1].ToString();
  28. // Adding.
  29. lst.Add(infoObj);
  30. }
  31. // Closing.
  32. sr.Dispose();
  33. sr.Close();
  34. }
  35. catch (Exception ex)
  36. {
  37. // info.
  38. Console.Write(ex);
  39. }
  40. // info.
  41. return lst;
  42. }
  43. #endregion

In the above method, I am simply loading my sample country list data extract from the ".txt" file into an in-memory list of type "CountryObj".

The second method that is created here is "GetCountryList()" method.

  1. #region Get country method.
  2. /// <summary>
  3. /// Get country method.
  4. /// </summary>
  5. /// <returns>Return country for drop down list.</returns>
  6. private IEnumerable<SelectListItem> GetCountryList()
  7. {
  8. // Initialization.
  9. SelectList lstobj = null;
  10. try
  11. {
  12. // Loading.
  13. var list = this.LoadData()
  14. .Select(p =>
  15. new SelectListItem
  16. {
  17. Value = p.Country_Id.ToString(),
  18. Text = p.Country_Name
  19. });
  20. // Setting.
  21. lstobj = new SelectList(list, "Value", "Text");
  22. }
  23. catch (Exception ex)
  24. {
  25. // Info
  26. throw ex;
  27. }
  28. // info.
  29. return lstobj;
  30. }
  31. #endregion

In the above method, I have converted my data list into the type that is acceptable by the Razor View Engine drop-down control.

Notice the following lines of codes in the above code.

  1. // Loading.
  2. var list = this.LoadData()
  3. .Select(p =>
  4. new SelectListItem
  5. {
  6. Value = p.Country_Id.ToString(),
  7. Text = p.Country_Name
  8. });
  9. // Setting.
  10. lstobj = new SelectList(list, "Value", "Text");

In the above lines of code, the text values i.e. "Value" & "Text" pass in the "SelectList" constructor are the properties of "SelectListItem" class. I am simply telling "SelectList" class that these two properties contain the dropdown display text value and the corresponding id value mapping.

The third method that is created here is GET "Index()" method i.e.

  1. #region Get: /MultiSelectDropDown/Index method.
  2. /// <summary>
  3. /// Get: /MultiSelectDropDown/Index method.
  4. /// </summary>
  5. /// <returns>Return index view</returns>
  6. public ActionResult Index()
  7. {
  8. // Initialization.
  9. MultiSelectDropDownViewModel model = new MultiSelectDropDownViewModel { SelectedMultiCountryId = new List<int>(), SelectedCountryLst = new List<CountryObj>() };
  10. try
  11. {
  12. // Loading drop down lists.
  13. this.ViewBag.CountryList = this.GetCountryList();
  14. }
  15. catch (Exception ex)
  16. {
  17. // Info
  18. Console.Write(ex);
  19. }
  20. // Info.
  21. return this.View(model);
  22. }
  23. #endregion

In the above code, I have mapped the dropdown list data into a view bag property, which will be used in Razor View control and done some basic initialization of my attached view model to the UI view.

The forth and the final created method is POST "Index(...)" method i.e.

  1. #region POST: /MultiSelectDropDown/Index
  2. /// <summary>
  3. /// POST: /MultiSelectDropDown/Index
  4. /// </summary>
  5. /// <param name="model">Model parameter</param>
  6. /// <returns>Return - Response information</returns>
  7. [HttpPost]
  8. [AllowAnonymous]
  9. [ValidateAntiForgeryToken]
  10. public ActionResult Index(MultiSelectDropDownViewModel model)
  11. {
  12. // Initialization.
  13. string filePath = string.Empty;
  14. string fileContentType = string.Empty;
  15. try
  16. {
  17. // Verification
  18. if (ModelState.IsValid)
  19. {
  20. // Initialization.
  21. List<CountryObj> countryList = this.LoadData();
  22. // Selected countries list.
  23. model.SelectedCountryLst = countryList.Where(p => model.SelectedMultiCountryId.Contains(p.Country_Id)).Select(q => q).ToList();
  24. }
  25. // Loading drop down lists.
  26. this.ViewBag.CountryList = this.GetCountryList();
  27. }
  28. catch (Exception ex)
  29. {
  30. // Info
  31. Console.Write(ex);
  32. }
  33. // Info
  34. return this.View(model);
  35. }
  36. #endregion

In the above code, I have populated & mapped the selected countries list into my model and then pass the Model back to the View.

Step 7

To, integrate the bootstrap style dropdown plugin bootsrtap-select. Create an new JavaScript "Scripts\script-bootstrap-select.js" file and replace the following code in it. i.e.

  1. $(document).ready(function ()
  2. {
  3. // Enable Live Search.
  4. $('#CountryList').attr('data-live-search', true);
  5. //// Enable multiple select.
  6. $('#CountryList').attr('multiple', true);
  7. $('#CountryList').attr('data-selected-text-format', 'count');
  8. $('.selectCountry').selectpicker(
  9. {
  10. width: '100%',
  11. title: '- [Choose Multiple Countries] -',
  12. style: 'btn-warning',
  13. size: 6,
  14. iconBase: 'fa',
  15. tickIcon: 'fa-check'
  16. });
  17. });

In the above code, I have called "slectpicker()" method of the bootstrap-select plugin with the basic settings. Before calling this method I have also set the live search property of the plugin, so, the end-user can search for the required value from the dropdown list. I have also set the multiple property as true which will enable the drop-down selection multiple and I have also set the text format property as count which will display the selection count for multi-select choice on the dropdown plugin.

Step 8

Now, create a view "Views\MultiSelectDropDown\Index.cshtml" file and replace the following code in it i.e.

  1. @using SaveMultiSelectDropDown.Models
  2. @model SaveMultiSelectDropDown.Models.MultiSelectDropDownViewModel
  3. @{
  4. ViewBag.Title = "ASP.NET MVC5: Multi Select Dropdown List";
  5. }
  6. <div class="row">
  7. <div class="panel-heading">
  8. <div class="col-md-8">
  9. <h3>
  10. <i class="fa fa-tags"></i>
  11. <span>ASP.NET MVC5: Multi Select Dropdown List</span>
  12. </h3>
  13. </div>
  14. </div>
  15. </div>
  16. <br />
  17. <div class="row">
  18. <div class="col-md-6 col-md-push-2">
  19. <section>
  20. @using (Html.BeginForm("Index", "MultiSelectDropDown", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" }))
  21. {
  22. @Html.AntiForgeryToken()
  23. <div class="well bs-component">
  24. <br />
  25. <div class="row">
  26. <div class="col-md-6 col-md-push-2">
  27. <div class="form-group">
  28. <div class="input-group">
  29. <span class="input-group-addon icon-custom"><i class="fa fa-flag"></i></span>
  30. @Html.ListBoxFor(m => m.SelectedMultiCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control input-md" })
  31. </div>
  32. </div>
  33. </div>
  34. <div class="col-md-6 col-md-push-2">
  35. <div class="form-group">
  36. <input type="submit" class="btn btn-danger" value="Select" />
  37. </div>
  38. </div>
  39. </div>
  40. </div>
  41. }
  42. </section>
  43. </div>
  44. </div>
  45. <hr />
  46. <div class="row">
  47. <div class="col-md-offset-4 col-md-8">
  48. <h3>List of Selected Countries </h3>
  49. </div>
  50. </div>
  51. <hr />
  52. @if (Model.SelectedCountryLst != null &&
  53. Model.SelectedCountryLst.Count > 0)
  54. {
  55. <div class="row">
  56. <div class="col-md-offset-1 col-md-8">
  57. <section>
  58. <table class="table table-bordered table-striped">
  59. <thead>
  60. <tr>
  61. <th style="text-align: center;">Sr.</th>
  62. <th style="text-align: center;">Country Name</th>
  63. </tr>
  64. </thead>
  65. <tbody>
  66. @for (int i = 0; i < Model.SelectedCountryLst.Count; i++)
  67. {
  68. <tr>
  69. <td style="text-align: center;">@(i + 1)</td>
  70. <td style="text-align: center;">@Model.SelectedCountryLst[i].Country_Name</td>
  71. </tr>
  72. }
  73. </tbody>
  74. </table>
  75. </section>
  76. </div>
  77. </div>
  78. }
  79. @section Scripts
  80. {
  81. @*Scripts*@
  82. @Scripts.Render("~/bundles/bootstrap-select")
  83. @*Styles*@
  84. @Styles.Render("~/Content/Bootstrap-Select/css")
  85. }

In the above code, I have created the multi-select drop-down control with Bootstrap style plugin integration. I have also created the display list which will display the list of multiple countries as the user makes multiple selection choices via bootstrap style drop-down plugin and finally, I have also linked the require reference libraries for bootstrap style plugin.

The below lines of code have enabled the multiple-selection in bootstrap style dropdown Razor View UI component. Notice here that instead of using traditional razor view drop-down list UI component, I am using razor view List box UI component simply because I am making my dropdown plugin a multi-selection choice UI component.

  1. <div class="input-group">
  2. <span class="input-group-addon icon-custom"><i class="fa fa-flag"></i></span>
  3. @Html.ListBoxFor(m => m.SelectedMultiCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control input-md" })
  4. </div>

Step 9

Now, execute the project and you will be able to see the bootstrap style multi-select dropdown plugin in action, as shown below.





Conclusion

In this article, you will learn about multiple selection via "Bootstrap Select" dropdown plugin. You will also learn about the integration of the bootstrap style plugin with ASP.NET MVC5 platform. You will also learn in this article about the creation of list data which is compatible with razor view engine. You will also learn to load data from text file and you will learn to utilize the multiple-select choice via the Bootstrap Select drop-down plugin.