ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin

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 in any Server side technology.

Today, I shall be demonstrating an integration of Bootstrap CSS style dropdown plugin Bootstrap which needs to be selected into ASP.NET MVC5 platform.

Following are some prerequisites before you proceed 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 given below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise. I am using Country table data extract from Adventure Works Sample database.

Let's begin now.

Step 1

Create a new MVC Web project and name it as BootstrapStyleDropdown.

Step 2

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

Step 3

Open the Views->Shared->_Layout.cshtml file and replace the code given below in it i.e.

  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.   
  10.     <!-- Font Awesome -->  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  12. </head>  
  13. <body>  
  14.     <div class="navbar navbar-inverse navbar-fixed-top">  
  15.         <div class="container">  
  16.             <div class="navbar-header">  
  17.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  18.                     <span class="icon-bar"></span>  
  19.                     <span class="icon-bar"></span>  
  20.                     <span class="icon-bar"></span>  
  21.                 </button>  
  22.             </div>  
  23.         </div>  
  24.     </div>  
  25.     <div class="container body-content">  
  26.         @RenderBody()  
  27.         <hr />  
  28.         <footer>  
  29.             <center>  
  30.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  31.             </center>  
  32.         </footer>  
  33.     </div>  
  34.   
  35.     @Scripts.Render("~/bundles/jquery")  
  36.     @Scripts.Render("~/bundles/bootstrap")  
  37.   
  38.   
  39.     @RenderSection("scripts", required: false)  
  40. </body>  
  41. </html> 

In the code given above, we have simply set our default layout of any page.

Step 4

Create a new file CountryObj.cs under Models folder and replace the code given below in it i.e.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace BootstrapStyleDropdown.Models  
  7. {  
  8.     public class CountryObj  
  9.     {  
  10.         public int Country_Id { getset; }  
  11.         public string Country_Name { getset; }  
  12.     }  

In the code given above, I have simply created an object class which will map my sample list data.

Step 5

Now, create another new file under Models folder and replace the code given below in it i.e

  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace BootstrapStyleDropdown.Models  
  5. {  
  6.     public class DropdownViewModel  
  7.     {  
  8.         [Display(Name = "Choose country")]  
  9.         public int? SelectedCountryId { getset; }  
  10.     }  

In the above code, I have created my view model which I will attach with my view. Notice that I have created a null-able integer property which will capture my selected value from the razor view dropdown control.

Step 6

Create a new "HomeController.cs" controller in "Controllers" folder and replace the following code in it i.e.

  1. //-----------------------------------------------------------------------  
  2. // <copyright file="HomeController.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace BootstrapStyleDropdown.Controllers  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.IO;  
  13.     using System.Linq;  
  14.     using System.Reflection;  
  15.     using System.Web;  
  16.     using System.Web.Mvc;  
  17.     using Models;  
  18.   
  19.     /// <summary>  
  20.     /// Home Controller class.  
  21.     /// </summary>  
  22.     public class HomeController : Controller  
  23.     {  
  24.         #region Index method  
  25.   
  26.         /// <summary>  
  27.         /// GET: Index method.  
  28.         /// </summary>  
  29.         /// <returns>Returns - index view page</returns>   
  30.         public ActionResult Index()  
  31.         {  
  32.             // Initialization.  
  33.             DropdownViewModel model = new DropdownViewModel();  
  34.   
  35.             // Settings.  
  36.             model.SelectedCountryId = 0;  
  37.   
  38.             // Loading drop down lists.  
  39.             this.ViewBag.CountryList = this.GetCountryList();  
  40.   
  41.             // Info.  
  42.             return this.View(model);  
  43.         }  
  44.  
  45.         #endregion  
  46.  
  47.         #region Helpers  
  48.  
  49.         #region Load Data  
  50.   
  51.         /// <summary>  
  52.         /// Load data method.  
  53.         /// </summary>  
  54.         /// <returns>Returns - Data</returns>  
  55.         private List<CountryObj> LoadData()  
  56.         {  
  57.             // Initialization.  
  58.             List<CountryObj> lst = new List<CountryObj>();  
  59.   
  60.             try  
  61.             {  
  62.                 // Initialization.  
  63.                 string line = string.Empty;  
  64.                 string srcFilePath = "content/files/country_list.txt";  
  65.                 var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);  
  66.                 var fullPath = Path.Combine(rootPath, srcFilePath);  
  67.                 string filePath = new Uri(fullPath).LocalPath;  
  68.                 StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));  
  69.   
  70.                 // Read file.  
  71.                 while ((line = sr.ReadLine()) != null)  
  72.                 {  
  73.                     // Initialization.  
  74.                     CountryObj infoObj = new CountryObj();  
  75.                     string[] info = line.Split(',');  
  76.   
  77.                     // Setting.  
  78.                     infoObj.Country_Id = Convert.ToInt32(info[0].ToString());  
  79.                     infoObj.Country_Name = info[1].ToString();  
  80.   
  81.                     // Adding.  
  82.                     lst.Add(infoObj);  
  83.                 }  
  84.   
  85.                 // Closing.  
  86.                 sr.Dispose();  
  87.                 sr.Close();  
  88.             }  
  89.             catch (Exception ex)  
  90.             {  
  91.                 // info.  
  92.                 Console.Write(ex);  
  93.             }  
  94.   
  95.             // info.  
  96.             return lst;  
  97.         }  
  98.  
  99.         #endregion  
  100.  
  101.         #region Get roles method.  
  102.   
  103.         /// <summary>  
  104.         /// Get country method.  
  105.         /// </summary>  
  106.         /// <returns>Return country for drop down list.</returns>  
  107.         private IEnumerable<SelectListItem> GetCountryList()  
  108.         {  
  109.             // Initialization.  
  110.             SelectList lstobj = null;  
  111.   
  112.             try  
  113.             {  
  114.                 // Loading.  
  115.                 var list = this.LoadData()  
  116.                                   .Select(p =>  
  117.                                             new SelectListItem  
  118.                                             {  
  119.                                                 Value = p.Country_Id.ToString(),  
  120.                                                 Text = p.Country_Name  
  121.                                             });  
  122.   
  123.                 // Setting.  
  124.                 lstobj = new SelectList(list, "Value""Text");  
  125.             }  
  126.             catch (Exception ex)  
  127.             {  
  128.                 // Info  
  129.                 throw ex;  
  130.             }  
  131.   
  132.             // info.  
  133.             return lstobj;  
  134.         }  
  135.  
  136.         #endregion  
  137.  
  138.         #endregion  
  139.     }  

In the code given above, I have created LoadData(), GetCountryList() & Index() methods. Let's break down each method and try to understand that what have we added here.

The first method that created here is LoadData() method i.e.

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

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

The second method that is created here is GetCountryList() method i.e.

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

In the method given above, I have converted my data list into type, which is acceptable by razor view engine dropdown control. Notice the lines of code in the code given above.

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

In the lines of code, the text value i.e. Value & Text is passed in the SelectList constructor are the properties of SelectListItem class. We are simply telling SelectList class that these two properties contains the dropdown, which displays the text value and the corresponding id mapping.

The third method, which is created here is Index() method i.e.

  1. #region Index method  
  2.   
  3. /// <summary>  
  4. /// GET: Index method.  
  5. /// </summary>  
  6. /// <returns>Returns - index view page</returns>   
  7. public ActionResult Index()  
  8. {  
  9.     // Initialization.  
  10.     DropdownViewModel model = new DropdownViewModel();  
  11.   
  12.     // Settings.  
  13.     model.SelectedCountryId = 0;  
  14.   
  15.     // Loading drop down lists.  
  16.     this.ViewBag.CountryList = this.GetCountryList();  
  17.   
  18.     // Info.  
  19.     return this.View(model);  
  20. }  
  21.  
  22. #endregion 

In the code given above, I have mapped the dropdown list data into a view bag property, which will be used in razor view control.

Step 7

Create a view Index.cshtml file under Views folder and replace the code given below in it i.e.

  1. @model BootstrapStyleDropdown.Models.DropdownViewModel  
  2. @{  
  3.     ViewBag.Title = "Bootstrap Style Dropdown";  
  4. }  
  5.   
  6. <h2>@ViewBag.Title.</h2>  
  7.   
  8. <section>  
  9.     <div class="well bs-component">  
  10.         <br />  
  11.   
  12.         <div class="row">  
  13.             <div class="col-xs-4 col-xs-push-0">  
  14.                 <div class="form-group">  
  15.                     @Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { @class = "form-control" })  
  16.                 </div>  
  17.             </div>  
  18.         </div>  
  19.     </div>  
  20. </section> 

In the code given above, we have created our dropdown control without Bootsrtap style plugin integration.

Step 8

Execute the project and you will see the result, as shown below with the integration of bootstrap style plugin integration.

 

Step 9

Now, let's integrate bootstrap style dropdown plugin bootstrap select. Create an new JavaScript "script-bootstrap-select.js" under "Scripts" folder and replace the code given below in it.

  1. $(document).ready(function ()   
  2. {  
  3.     // Enable Live Search.  
  4.     $('#CountryList').attr('data-live-search'true);  
  5.   
  6.     $('.selectCountry').selectpicker(  
  7.     {  
  8.         width: '100%',  
  9.         title: '- [Choose Country] -',  
  10.         style: 'btn-warning',  
  11.         size: 6  
  12.     });  
  13. });   

In the code given above, 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 require value from the dropdown list.

Step 10

Open Index.cshtml file and replace the code given below in it i.e.

  1. @model BootstrapStyleDropdown.Models.DropdownViewModel  
  2. @{  
  3.     ViewBag.Title = "Bootstrap Style Dropdown";  
  4. }  
  5.   
  6. <h2>@ViewBag.Title.</h2>  
  7.   
  8. <section>  
  9.     <div class="well bs-component">  
  10.         <br />  
  11.   
  12.         <div class="row">  
  13.             <div class="col-xs-4 col-xs-push-0">  
  14.                 <div class="form-group">  
  15.                     @Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control" })  
  16.                 </div>  
  17.             </div>  
  18.         </div>  
  19.     </div>  
  20. </section>  
  21.   
  22. @section Scripts   
  23. {  
  24.     @*Scripts*@  
  25.     @Scripts.Render("~/bundles/bootstrap-select")  
  26.   
  27.     @*Styles*@  
  28.     @Styles.Render("~/Content/Bootstrap-Select/css")  

In the code given above, we have added reference links of Bootstrap Select plugin and set HTML ID and classes related to plugin settings.

Step 11

Now, execute the project and you will see bootstrap style dropdown plugin in an action, as shown below i.e.


Conclusion

In this article, you learned about Bootstrap Select" dropdown plugin. You also learned about the integration of the bootstrap style plugin with ASP.NET MVC5 platform. In addition to it, you have learned about the creation of list data which is compatible with razor view engine.

Up Next
    Ebook Download
    View all
    Learn
    View all