ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin (2024)

ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin (1)

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.

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

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4. <metacharset="utf-8"/>
  5. <metaname="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. <!--FontAwesome-->
  10. <linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"/>
  11. </head>
  12. <body>
  13. <divclass="navbarnavbar-inversenavbar-fixed-top">
  14. <divclass="container">
  15. <divclass="navbar-header">
  16. <buttontype="button"class="navbar-toggle"data-toggle="collapse"data-target=".navbar-collapse">
  17. <spanclass="icon-bar"></span>
  18. <spanclass="icon-bar"></span>
  19. <spanclass="icon-bar"></span>
  20. </button>
  21. </div>
  22. </div>
  23. </div>
  24. <divclass="containerbody-content">
  25. @RenderBody()
  26. <hr/>
  27. <footer>
  28. <center>
  29. <p><strong>Copyright©@DateTime.Now.Year-<ahref="http://www.asmak9.com/">Asma'sBlog</a>.</strong>Allrightsreserved.</p>
  30. </center>
  31. </footer>
  32. </div>
  33. @Scripts.Render("~/bundles/jquery")
  34. @Scripts.Render("~/bundles/bootstrap")
  35. @RenderSection("scripts",required:false)
  36. </body>
  37. </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. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. namespaceBootstrapStyleDropdown.Models
  6. {
  7. publicclassCountryObj
  8. {
  9. publicintCountry_Id{get;set;}
  10. publicstringCountry_Name{get;set;}
  11. }
  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. usingSystem.Collections.Generic;
  2. usingSystem.ComponentModel.DataAnnotations;
  3. namespaceBootstrapStyleDropdown.Models
  4. {
  5. publicclassDropdownViewModel
  6. {
  7. [Display(Name="Choosecountry")]
  8. publicint?SelectedCountryId{get;set;}
  9. }
  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. //<copyrightfile="HomeController.cs"company="None">
  3. //Copyright(c)Allowtodistributethiscode.
  4. //</copyright>
  5. //<author>AsmaKhalid</author>
  6. //-----------------------------------------------------------------------
  7. namespaceBootstrapStyleDropdown.Controllers
  8. {
  9. usingSystem;
  10. usingSystem.Collections.Generic;
  11. usingSystem.IO;
  12. usingSystem.Linq;
  13. usingSystem.Reflection;
  14. usingSystem.Web;
  15. usingSystem.Web.Mvc;
  16. usingModels;
  17. ///<summary>
  18. ///HomeControllerclass.
  19. ///</summary>
  20. publicclassHomeController:Controller
  21. {
  22. #regionIndexmethod
  23. ///<summary>
  24. ///GET:Indexmethod.
  25. ///</summary>
  26. ///<returns>Returns-indexviewpage</returns>
  27. publicActionResultIndex()
  28. {
  29. //Initialization.
  30. DropdownViewModelmodel=newDropdownViewModel();
  31. //Settings.
  32. model.SelectedCountryId=0;
  33. //Loadingdropdownlists.
  34. this.ViewBag.CountryList=this.GetCountryList();
  35. //Info.
  36. returnthis.View(model);
  37. }
  38. #endregion
  39. #regionHelpers
  40. #regionLoadData
  41. ///<summary>
  42. ///Loaddatamethod.
  43. ///</summary>
  44. ///<returns>Returns-Data</returns>
  45. privateList<CountryObj>LoadData()
  46. {
  47. //Initialization.
  48. List<CountryObj>lst=newList<CountryObj>();
  49. try
  50. {
  51. //Initialization.
  52. stringline=string.Empty;
  53. stringsrcFilePath="content/files/country_list.txt";
  54. varrootPath=Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
  55. varfullPath=Path.Combine(rootPath,srcFilePath);
  56. stringfilePath=newUri(fullPath).LocalPath;
  57. StreamReadersr=newStreamReader(newFileStream(filePath,FileMode.Open,FileAccess.Read));
  58. //Readfile.
  59. while((line=sr.ReadLine())!=null)
  60. {
  61. //Initialization.
  62. CountryObjinfoObj=newCountryObj();
  63. string[]info=line.Split(',');
  64. //Setting.
  65. infoObj.Country_Id=Convert.ToInt32(info[0].ToString());
  66. infoObj.Country_Name=info[1].ToString();
  67. //Adding.
  68. lst.Add(infoObj);
  69. }
  70. //Closing.
  71. sr.Dispose();
  72. sr.Close();
  73. }
  74. catch(Exceptionex)
  75. {
  76. //info.
  77. Console.Write(ex);
  78. }
  79. //info.
  80. returnlst;
  81. }
  82. #endregion
  83. #regionGetrolesmethod.
  84. ///<summary>
  85. ///Getcountrymethod.
  86. ///</summary>
  87. ///<returns>Returncountryfordropdownlist.</returns>
  88. privateIEnumerable<SelectListItem>GetCountryList()
  89. {
  90. //Initialization.
  91. SelectListlstobj=null;
  92. try
  93. {
  94. //Loading.
  95. varlist=this.LoadData()
  96. .Select(p=>
  97. newSelectListItem
  98. {
  99. Value=p.Country_Id.ToString(),
  100. Text=p.Country_Name
  101. });
  102. //Setting.
  103. lstobj=newSelectList(list,"Value","Text");
  104. }
  105. catch(Exceptionex)
  106. {
  107. //Info
  108. throwex;
  109. }
  110. //info.
  111. returnlstobj;
  112. }
  113. #endregion
  114. #endregion
  115. }
  116. }

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. #regionLoadData
  2. ///<summary>
  3. ///Loaddatamethod.
  4. ///</summary>
  5. ///<returns>Returns-Data</returns>
  6. privateList<CountryObj>LoadData()
  7. {
  8. //Initialization.
  9. List<CountryObj>lst=newList<CountryObj>();
  10. try
  11. {
  12. //Initialization.
  13. stringline=string.Empty;
  14. stringsrcFilePath="content/files/country_list.txt";
  15. varrootPath=Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
  16. varfullPath=Path.Combine(rootPath,srcFilePath);
  17. stringfilePath=newUri(fullPath).LocalPath;
  18. StreamReadersr=newStreamReader(newFileStream(filePath,FileMode.Open,FileAccess.Read));
  19. //Readfile.
  20. while((line=sr.ReadLine())!=null)
  21. {
  22. //Initialization.
  23. CountryObjinfoObj=newCountryObj();
  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(Exceptionex)
  36. {
  37. //info.
  38. Console.Write(ex);
  39. }
  40. //info.
  41. returnlst;
  42. }
  43. #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. #regionGetcountrymethod.
  2. ///<summary>
  3. ///Getcountrymethod.
  4. ///</summary>
  5. ///<returns>Returncountryfordropdownlist.</returns>
  6. privateIEnumerable<SelectListItem>GetCountryList()
  7. {
  8. //Initialization.
  9. SelectListlstobj=null;
  10. try
  11. {
  12. //Loading.
  13. varlist=this.LoadData()
  14. .Select(p=>
  15. newSelectListItem
  16. {
  17. Value=p.Country_Id.ToString(),
  18. Text=p.Country_Name
  19. });
  20. //Setting.
  21. lstobj=newSelectList(list,"Value","Text");
  22. }
  23. catch(Exceptionex)
  24. {
  25. //Info
  26. throwex;
  27. }
  28. //info.
  29. returnlstobj;
  30. }
  31. #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. varlist=this.LoadData()
  2. .Select(p=>
  3. newSelectListItem
  4. {
  5. Value=p.Country_Id.ToString(),
  6. Text=p.Country_Name
  7. });
  8. //Setting.
  9. 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.

  1. #regionIndexmethod
  2. ///<summary>
  3. ///GET:Indexmethod.
  4. ///</summary>
  5. ///<returns>Returns-indexviewpage</returns>
  6. publicActionResultIndex()
  7. {
  8. //Initialization.
  9. DropdownViewModelmodel=newDropdownViewModel();
  10. //Settings.
  11. model.SelectedCountryId=0;
  12. //Loadingdropdownlists.
  13. this.ViewBag.CountryList=this.GetCountryList();
  14. //Info.
  15. returnthis.View(model);
  16. }
  17. #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. @modelBootstrapStyleDropdown.Models.DropdownViewModel
  2. @{
  3. ViewBag.Title="BootstrapStyleDropdown";
  4. }
  5. <h2>@ViewBag.Title.</h2>
  6. <section>
  7. <divclass="wellbs-component">
  8. <br/>
  9. <divclass="row">
  10. <divclass="col-xs-4col-xs-push-0">
  11. <divclass="form-group">
  12. @Html.DropDownListFor(m=>m.SelectedCountryId,this.ViewBag.CountryListasSelectList,new{@class="form-control"})
  13. </div>
  14. </div>
  15. </div>
  16. </div>
  17. </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.

ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin (2)

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. //EnableLiveSearch.
  4. $('#CountryList').attr('data-live-search',true);
  5. $('.selectCountry').selectpicker(
  6. {
  7. width:'100%',
  8. title:'-[ChooseCountry]-',
  9. style:'btn-warning',
  10. size:6
  11. });
  12. });

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. @modelBootstrapStyleDropdown.Models.DropdownViewModel
  2. @{
  3. ViewBag.Title="BootstrapStyleDropdown";
  4. }
  5. <h2>@ViewBag.Title.</h2>
  6. <section>
  7. <divclass="wellbs-component">
  8. <br/>
  9. <divclass="row">
  10. <divclass="col-xs-4col-xs-push-0">
  11. <divclass="form-group">
  12. @Html.DropDownListFor(m=>m.SelectedCountryId,this.ViewBag.CountryListasSelectList,new{id="CountryList",@class="selectCountryshow-tickform-control"})
  13. </div>
  14. </div>
  15. </div>
  16. </div>
  17. </section>
  18. @sectionScripts
  19. {
  20. @*Scripts*@
  21. @Scripts.Render("~/bundles/bootstrap-select")
  22. @*Styles*@
  23. @Styles.Render("~/Content/Bootstrap-Select/css")
  24. }

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.

ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin (3)
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.

ASP.NET MVC 5 - Bootstrap Style Dropdown Plugin (2024)
Top Articles
Network Handoff: The Ultimate Guide
Find Answers | iRobot
Ups Customer Center Locations
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Bj 사슴이 분수
Week 2 Defense (DEF) Streamers, Starters & Rankings: 2024 Fantasy Tiers, Rankings
Hotels Near 500 W Sunshine St Springfield Mo 65807
Hardly Antonyms
Corporate Homepage | Publix Super Markets
Tiraj Bòlèt Florida Soir
Knaben Pirate Download
2016 Hyundai Sonata Price, Value, Depreciation & Reviews | Kelley Blue Book
Aspen.sprout Forum
Busty Bruce Lee
Peraton Sso
Teenleaks Discord
Dr Adj Redist Cadv Prin Amex Charge
Bj Alex Mangabuddy
Video shows two planes collide while taxiing at airport | CNN
Craigslist In Visalia California
Unity - Manual: Scene view navigation
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
Accident On The 210 Freeway Today
Trivago Myrtle Beach Hotels
Barista Breast Expansion
Dell 22 FHD-Computermonitor – E2222H | Dell Deutschland
Mawal Gameroom Download
Ofw Pinoy Channel Su
Grandstand 13 Fenway
Craigslist Free Stuff San Gabriel Valley
Nail Salon Open On Monday Near Me
JD Power's top airlines in 2024, ranked - The Points Guy
Σινεμά - Τι Ταινίες Παίζουν οι Κινηματογράφοι Σήμερα - Πρόγραμμα 2024 | iathens.gr
Workday Latech Edu
Senior Houses For Sale Near Me
Montrose Colorado Sheriff's Department
Craigslist Lakeside Az
Ishow Speed Dick Leak
Hellgirl000
Invalleerkracht [Gratis] voorbeelden van sollicitatiebrieven & expert tips
Emulating Web Browser in a Dedicated Intermediary Box
התחבר/י או הירשם/הירשמי כדי לראות.
Honkai Star Rail Aha Stuffed Toy
Victoria Vesce Playboy
Stitch And Angel Tattoo Black And White
Accident On 40 East Today
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Myhrkohls.con
Deviantart Rwby
Gelato 47 Allbud
Invitation Quinceanera Espanol
Latest Posts
Article information

Author: Velia Krajcik

Last Updated:

Views: 5874

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.