Header Ads

ASP.NET MVC5: Bootstrap Style Dropdown Plugin


One of the cool thing about Bootstrap CSS framework is that it provides a very rich and interactive built-in plugins, which are easy to use and integrate in any server side technology.
Today, I shall be demonstrating integration of the Bootsrtap CSS style dropdown plugin Bootstrap Select 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 Adventure Works Sample Database.

Download Now!

Let's begin now.

1) Create a new MVC web project and name it "BootstrapStyleDropdown".  
2) Now download the "Bootstrap Select" plugin and place the respective JavaScript & CSS files into "Scripts" & "Content->style" folders.
3) Open the "Views->Shared->_Layout.cshtml" file and replace following code in it i.e.


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <center>
                <p><strong>Copyright &copy; @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
            </center>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")


    @RenderSection("scripts", required: false)
</body>
</html>

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

4) Create a new file "CountryObj.cs" under Models folder and replace the following code in it i.e.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BootstrapStyleDropdown.Models
{
    public class CountryObj
    {
        public int Country_Id { get; set; }
        public string Country_Name { get; set; }
    }
}

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

5) Now, create another new file "Models\DropdownViewModel.cs" under Models folder and replace the following code in it i.e


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BootstrapStyleDropdown.Models
{
    public class DropdownViewModel
    {
        [Display(Name = "Choose country")]
        public int? SelectedCountryId { get; set; }
    }
}

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.

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


//-----------------------------------------------------------------------
// <copyright file="HomeController.cs" company="None">
//     Copyright (c) Allow to distribute this code.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace BootstrapStyleDropdown.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;
    using Models;

    /// <summary>
    /// Home Controller class.
    /// </summary>
    public class HomeController : Controller
    {
        #region Index method

        /// <summary>
        /// GET: Index method.
        /// </summary>
        /// <returns>Returns - index view page</returns> 
        public ActionResult Index()
        {
            // Initialization.
            DropdownViewModel model = new DropdownViewModel();

            // Settings.
            model.SelectedCountryId = 0;

            // Loading drop down lists.
            this.ViewBag.CountryList = this.GetCountryList();

            // Info.
            return this.View(model);
        }

        #endregion

        #region Helpers

        #region Load Data

        /// <summary>
        /// Load data method.
        /// </summary>
        /// <returns>Returns - Data</returns>
        private List<CountryObj> LoadData()
        {
            // Initialization.
            List<CountryObj> lst = new List<CountryObj>();

            try
            {
                // Initialization.
                string line = string.Empty;
                string srcFilePath = "content/files/country_list.txt";
                var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                var fullPath = Path.Combine(rootPath, srcFilePath);
                string filePath = new Uri(fullPath).LocalPath;
                StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));

                // Read file.
                while ((line = sr.ReadLine()) != null)
                {
                    // Initialization.
                    CountryObj infoObj = new CountryObj();
                    string[] info = line.Split(',');

                    // Setting.
                    infoObj.Country_Id = Convert.ToInt32(info[0].ToString());
                    infoObj.Country_Name = info[1].ToString();

                    // Adding.
                    lst.Add(infoObj);
                }

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

        #endregion

        #region Get roles method.

        /// <summary>
        /// Get country method.
        /// </summary>
        /// <returns>Return country for drop down list.</returns>
        private IEnumerable<SelectListItem> GetCountryList()
        {
            // Initialization.
            SelectList lstobj = null;

            try
            {
                // Loading.
                var list = this.LoadData()
                                  .Select(p =>
                                            new SelectListItem
                                            {
                                                Value = p.Country_Id.ToString(),
                                                Text = p.Country_Name
                                            });

                // Setting.
                lstobj = new SelectList(list, "Value", "Text");
            }
            catch (Exception ex)
            {
                // Info
                throw ex;
            }

            // info.
            return lstobj;
        }

        #endregion

        #endregion
    }
}

In the above code, 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 is created here is "LoadData()" method i.e.


        #region Load Data

        /// <summary>
        /// Load data method.
        /// </summary>
        /// <returns>Returns - Data</returns>
        private List<CountryObj> LoadData()
        {
            // Initialization.
            List<CountryObj> lst = new List<CountryObj>();

            try
            {
                // Initialization.
                string line = string.Empty;
                string srcFilePath = "content/files/country_list.txt";
                var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                var fullPath = Path.Combine(rootPath, srcFilePath);
                string filePath = new Uri(fullPath).LocalPath;
                StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));

                // Read file.
                while ((line = sr.ReadLine()) != null)
                {
                    // Initialization.
                    CountryObj infoObj = new CountryObj();
                    string[] info = line.Split(',');

                    // Setting.
                    infoObj.Country_Id = Convert.ToInt32(info[0].ToString());
                    infoObj.Country_Name = info[1].ToString();

                    // Adding.
                    lst.Add(infoObj);
                }

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

        #endregion

In the above method, 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.


       #region Get country method.

        /// <summary>
        /// Get country method.
        /// </summary>
        /// <returns>Return country for drop down list.</returns>
        private IEnumerable<SelectListItem> GetCountryList()
        {
            // Initialization.
            SelectList lstobj = null;

            try
            {
                // Loading.
                var list = this.LoadData()
                                  .Select(p =>
                                            new SelectListItem
                                            {
                                                Value = p.Country_Id.ToString(),
                                                Text = p.Country_Name
                                            });

                // Setting.
                lstobj = new SelectList(list, "Value", "Text");
            }
            catch (Exception ex)
            {
                // Info
                throw ex;
            }

            // info.
            return lstobj;
        }

        #endregion

 In the above method, I have converted my data list into type that is acceptable by razor view engine dropdown control. Notice following line of codes in the above code i.e.


               var list = this.LoadData()
                                  .Select(p =>
                                            new SelectListItem
                                            {
                                                Value = p.Country_Id.ToString(),
                                                Text = p.Country_Name
                                            });

                // Setting.
                lstobj = new SelectList(list, "Value", "Text");

In the above lines of code the text value i.e. "Value" & "Text" pass in the "SelectList" constructor are the properties of "SelectListItem" class. We are simply telling "SelectList" class that these two properties contain the dropdown displayed text value and the corresponding id mapping. The third method that is created here is "Index()" method i.e.


        #region Index method

        /// <summary>
        /// GET: Index method.
        /// </summary>
        /// <returns>Returns - index view page</returns> 
        public ActionResult Index()
        {
            // Initialization.
            DropdownViewModel model = new DropdownViewModel();

            // Settings.
            model.SelectedCountryId = 0;

            // Loading drop down lists.
            this.ViewBag.CountryList = this.GetCountryList();

            // Info.
            return this.View(model);
        }

        #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.

7) Create a view "Index.cshtml" file under "Views" folder and replace following code in it i.e.


@model BootstrapStyleDropdown.Models.DropdownViewModel
@{
    ViewBag.Title = "Bootstrap Style Dropdown";
}

<h2>@ViewBag.Title.</h2>

<section>
    <div class="well bs-component">
        <br />

        <div class="row">
            <div class="col-xs-4 col-xs-push-0">
                <div class="form-group">
                    @Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { @class = "form-control" })
                </div>
            </div>
        </div>
    </div>
</section>

In the above code, I have created a dropdown control without the Bootsrtap style plugin integration.

8) Execute the project and you will see result as shown below without the integration of bootsrtap style plugin.


9) Now, let's integrate bootstrap style dropdown plugin i.e. bootsrtap select. Create an new JavaScript "script-bootstrap-select.js" under "Scripts" folder and replace following code in it.


$(document).ready(function () 
{
    // Enable Live Search.
    $('#CountryList').attr('data-live-search', true);

    $('.selectCountry').selectpicker(
    {
        width: '100%',
        title: '- [Choose Country] -',
        style: 'btn-warning',
        size: 6
    });
});  

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 require value from the dropdown list easily.  

10) Open the "Index.cshtml" file and replace the following code in it i.e.


@model BootstrapStyleDropdown.Models.DropdownViewModel
@{
    ViewBag.Title = "Bootstrap Style Dropdown";
}

<h2>@ViewBag.Title.</h2>

<section>
    <div class="well bs-component">
        <br />

        <div class="row">
            <div class="col-xs-4 col-xs-push-0">
                <div class="form-group">
                    @Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control" })
                </div>
            </div>
        </div>
    </div>
</section>

@section Scripts 
{
    @*Scripts*@
    @Scripts.Render("~/bundles/bootstrap-select")

    @*Styles*@
    @Styles.Render("~/Content/Bootstrap-Select/css")
}

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

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


Conclusion

In this article, you will learn about the "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.

No comments