One of the cool things about theBootstrap 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 anintegration of Bootstrap CSS style dropdown plugin Bootstrap which needs to be selectedinto ASP.NET MVC5 platform.
Following are some prerequisites before you proceed further in this tutorial.
- Knowledge of ASP.NET MVC5.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of Jquery.
- 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 1Create a new MVC Web project and name it asBootstrapStyleDropdown.
Step 2Now, downloadBootstrap Select. Plugin and place the respective JavaScript & CSS files into Scripts & Content->style folders.
Step 3Open the Views->Shared->_Layout.cshtmlfile and replace the code given below in it i.e.
- <!DOCTYPEhtml>
- <html>
- <head>
- <metacharset="utf-8"/>
- <metaname="viewport"content="width=device-width,initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <!--FontAwesome-->
- <linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"/>
- </head>
- <body>
- <divclass="navbarnavbar-inversenavbar-fixed-top">
- <divclass="container">
- <divclass="navbar-header">
- <buttontype="button"class="navbar-toggle"data-toggle="collapse"data-target=".navbar-collapse">
- <spanclass="icon-bar"></span>
- <spanclass="icon-bar"></span>
- <spanclass="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <divclass="containerbody-content">
- @RenderBody()
- <hr/>
- <footer>
- <center>
- <p><strong>Copyright©@DateTime.Now.Year-<ahref="http://www.asmak9.com/">Asma'sBlog</a>.</strong>Allrightsreserved.</p>
- </center>
- </footer>
- </div>
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts",required:false)
- </body>
- </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.
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- namespaceBootstrapStyleDropdown.Models
- {
- publicclassCountryObj
- {
- publicintCountry_Id{get;set;}
- publicstringCountry_Name{get;set;}
- }
- }
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
- usingSystem.Collections.Generic;
- usingSystem.ComponentModel.DataAnnotations;
- namespaceBootstrapStyleDropdown.Models
- {
- publicclassDropdownViewModel
- {
- [Display(Name="Choosecountry")]
- publicint?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.
Step 6
Create a new "HomeController.cs" controller in "Controllers" folder and replace the following code in it i.e.
- //-----------------------------------------------------------------------
- //<copyrightfile="HomeController.cs"company="None">
- //Copyright(c)Allowtodistributethiscode.
- //</copyright>
- //<author>AsmaKhalid</author>
- //-----------------------------------------------------------------------
- namespaceBootstrapStyleDropdown.Controllers
- {
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.IO;
- usingSystem.Linq;
- usingSystem.Reflection;
- usingSystem.Web;
- usingSystem.Web.Mvc;
- usingModels;
- ///<summary>
- ///HomeControllerclass.
- ///</summary>
- publicclassHomeController:Controller
- {
- #regionIndexmethod
- ///<summary>
- ///GET:Indexmethod.
- ///</summary>
- ///<returns>Returns-indexviewpage</returns>
- publicActionResultIndex()
- {
- //Initialization.
- DropdownViewModelmodel=newDropdownViewModel();
- //Settings.
- model.SelectedCountryId=0;
- //Loadingdropdownlists.
- this.ViewBag.CountryList=this.GetCountryList();
- //Info.
- returnthis.View(model);
- }
- #endregion
- #regionHelpers
- #regionLoadData
- ///<summary>
- ///Loaddatamethod.
- ///</summary>
- ///<returns>Returns-Data</returns>
- privateList<CountryObj>LoadData()
- {
- //Initialization.
- List<CountryObj>lst=newList<CountryObj>();
- try
- {
- //Initialization.
- stringline=string.Empty;
- stringsrcFilePath="content/files/country_list.txt";
- varrootPath=Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- varfullPath=Path.Combine(rootPath,srcFilePath);
- stringfilePath=newUri(fullPath).LocalPath;
- StreamReadersr=newStreamReader(newFileStream(filePath,FileMode.Open,FileAccess.Read));
- //Readfile.
- while((line=sr.ReadLine())!=null)
- {
- //Initialization.
- CountryObjinfoObj=newCountryObj();
- 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(Exceptionex)
- {
- //info.
- Console.Write(ex);
- }
- //info.
- returnlst;
- }
- #endregion
- #regionGetrolesmethod.
- ///<summary>
- ///Getcountrymethod.
- ///</summary>
- ///<returns>Returncountryfordropdownlist.</returns>
- privateIEnumerable<SelectListItem>GetCountryList()
- {
- //Initialization.
- SelectListlstobj=null;
- try
- {
- //Loading.
- varlist=this.LoadData()
- .Select(p=>
- newSelectListItem
- {
- Value=p.Country_Id.ToString(),
- Text=p.Country_Name
- });
- //Setting.
- lstobj=newSelectList(list,"Value","Text");
- }
- catch(Exceptionex)
- {
- //Info
- throwex;
- }
- //info.
- returnlstobj;
- }
- #endregion
- #endregion
- }
- }
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.
- #regionLoadData
- ///<summary>
- ///Loaddatamethod.
- ///</summary>
- ///<returns>Returns-Data</returns>
- privateList<CountryObj>LoadData()
- {
- //Initialization.
- List<CountryObj>lst=newList<CountryObj>();
- try
- {
- //Initialization.
- stringline=string.Empty;
- stringsrcFilePath="content/files/country_list.txt";
- varrootPath=Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- varfullPath=Path.Combine(rootPath,srcFilePath);
- stringfilePath=newUri(fullPath).LocalPath;
- StreamReadersr=newStreamReader(newFileStream(filePath,FileMode.Open,FileAccess.Read));
- //Readfile.
- while((line=sr.ReadLine())!=null)
- {
- //Initialization.
- CountryObjinfoObj=newCountryObj();
- 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(Exceptionex)
- {
- //info.
- Console.Write(ex);
- }
- //info.
- returnlst;
- }
- #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.
- #regionGetcountrymethod.
- ///<summary>
- ///Getcountrymethod.
- ///</summary>
- ///<returns>Returncountryfordropdownlist.</returns>
- privateIEnumerable<SelectListItem>GetCountryList()
- {
- //Initialization.
- SelectListlstobj=null;
- try
- {
- //Loading.
- varlist=this.LoadData()
- .Select(p=>
- newSelectListItem
- {
- Value=p.Country_Id.ToString(),
- Text=p.Country_Name
- });
- //Setting.
- lstobj=newSelectList(list,"Value","Text");
- }
- catch(Exceptionex)
- {
- //Info
- throwex;
- }
- //info.
- returnlstobj;
- }
- #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.
- varlist=this.LoadData()
- .Select(p=>
- newSelectListItem
- {
- Value=p.Country_Id.ToString(),
- Text=p.Country_Name
- });
- //Setting.
- lstobj=newSelectList(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.
- #regionIndexmethod
- ///<summary>
- ///GET:Indexmethod.
- ///</summary>
- ///<returns>Returns-indexviewpage</returns>
- publicActionResultIndex()
- {
- //Initialization.
- DropdownViewModelmodel=newDropdownViewModel();
- //Settings.
- model.SelectedCountryId=0;
- //Loadingdropdownlists.
- this.ViewBag.CountryList=this.GetCountryList();
- //Info.
- returnthis.View(model);
- }
- #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.
- @modelBootstrapStyleDropdown.Models.DropdownViewModel
- @{
- ViewBag.Title="BootstrapStyleDropdown";
- }
- <h2>@ViewBag.Title.</h2>
- <section>
- <divclass="wellbs-component">
- <br/>
- <divclass="row">
- <divclass="col-xs-4col-xs-push-0">
- <divclass="form-group">
- @Html.DropDownListFor(m=>m.SelectedCountryId,this.ViewBag.CountryListasSelectList,new{@class="form-control"})
- </div>
- </div>
- </div>
- </div>
- </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 theresult, 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.
- $(document).ready(function()
- {
- //EnableLiveSearch.
- $('#CountryList').attr('data-live-search',true);
- $('.selectCountry').selectpicker(
- {
- width:'100%',
- title:'-[ChooseCountry]-',
- style:'btn-warning',
- size:6
- });
- });
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.
- @modelBootstrapStyleDropdown.Models.DropdownViewModel
- @{
- ViewBag.Title="BootstrapStyleDropdown";
- }
- <h2>@ViewBag.Title.</h2>
- <section>
- <divclass="wellbs-component">
- <br/>
- <divclass="row">
- <divclass="col-xs-4col-xs-push-0">
- <divclass="form-group">
- @Html.DropDownListFor(m=>m.SelectedCountryId,this.ViewBag.CountryListasSelectList,new{id="CountryList",@class="selectCountryshow-tickform-control"})
- </div>
- </div>
- </div>
- </div>
- </section>
- @sectionScripts
- {
- @*Scripts*@
- @Scripts.Render("~/bundles/bootstrap-select")
- @*Styles*@
- @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 havelearned about the creation of list data which is compatible with razor view engine.