This article is in continuation of my previous article on creating a multiselect dropdownlist using bootstrap in ASP.NET. If you haven’t had a look at it please go through the following link.

In the above article we simply developed a bootstrap Multiselect DropDownList user control with less features. The following are the merits and demerits of the built control:

Merits

Demerits

In this article we’ll try to enhance our user control so that all the drawbacks can be taken care of. So let’s update our control properties and script files accordingly.

AutoCompleteDdl.aspx code

  1. <%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="AutoCompleteDdl.ascx.cs"Inherits="User_Control_AutoCompleteDdl"%>
  2. <divstyledivstyledivstyledivstyledivstyledivstyledivstyledivstyle="width: 380px;"id="divAutoComplete"runat="server">
  3. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnButtonWidth"runat="server"Value="320px"/>
  4. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnNonSelectedText"runat="server"Value="--Select--"/>
  5. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnIncludeSelectAllOption"runat="server"Value="false"/>
  6. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnSelectAllText"runat="server"Value="All"/>
  7. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnEnableFiltering"runat="server"Value="False"/>
  8. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnEnableFilteringIgnoreCase"runat="server"Value="False"/>
  9. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnDisableIfEmpty"runat="server"Value="False"/>
  10. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnMaxHeight"runat="server"Value="200"/>
  11. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnFilterPlaceholder"runat="server"Value="Search for something..."/>
  12. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnAllSelectedText"runat="server"Value="No option left..."/>
  13. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnText"runat="server"/>
  14. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnValue"runat="server"/>
  15. <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnSelectionMode"runat="server"Value="checkbox"/>
  16. <asp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxID="ddlAutoCompleteSelect"runat="server"Style="width: 350px;"
  17. SelectionMode="Multiple"OnSelectedIndexChanged="ddlAutoCompleteSelect_SelectedIndexChanged1">
  18. </asp:ListBox>
  19. <!--Adding RequiredField Validator-->
  20. <asp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorID="reqddlAutoCompleteSelect"runat="server"ControlToValidate="ddlAutoCompleteSelect"
  21. InitialValue=""Display="Dynamic"Enabled="False"ForeColor="Red">
  22. </asp:RequiredFieldValidator>
  23. <p>
  24. <asp:LabelIDasp:LabelIDasp:LabelIDasp:LabelIDasp:LabelIDasp:LabelIDasp:LabelIDasp:LabelID="lblSelectedItems"runat="server"Style="word-wrap: break-word; height: auto; float: left; overflow-y: auto; display: none;">
  25. </asp:Label>
  26. </p>
  27. </div>
AutoCompleteDdl.aspx.cs
  1. using System;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Web.UI;
  6. usingSystem.Web.UI.WebControls;
  7. publicpartialclassUser_Control_AutoCompleteDdl: System.Web.UI.UserControl {#region Variable Declarations
  8. privateconststring _dataTextField = "Text";
  9. privateconststring _dataValueField = "Value";
  10. publiceventEventHandlerSelectedIndexChanged;
  11. #endregion
  12. #region Properties
  13. #regionBootStrap Properties
  14. ///<summary>
  15. ///Set the placeholder for the DropDownlist.
  16. ///</summary>
  17. publicstringNonSelectedText
  18. {
  19. get
  20. {
  21. returnhdnNonSelectedText.Value;
  22. }
  23. set
  24. {
  25. hdnNonSelectedText.Value = value;
  26. }
  27. }
  28. ///<summary>
  29. /// Get Or Set the value whether select all option should be included or not.
  30. ///</summary>
  31. publicboolIncludeSelectAllOption
  32. {
  33. get
  34. {
  35. returnConvert.ToBoolean(hdnIncludeSelectAllOption.Value);
  36. }
  37. set
  38. {
  39. //For radio Button or Single Select there is no need of including the selectAll Option/checkBox button.
  40. //That's why the default value of "false" is set even if the value is "True".
  41. if (value == true && SelectionMode == ListSelectionMode.Single) {
  42. hdnIncludeSelectAllOption.Value = "false";
  43. }
  44. else
  45. {
  46. hdnIncludeSelectAllOption.Value = Convert.ToString(value);
  47. }
  48. }
  49. }
  50. ///<summary>
  51. /// Get Or Set the value wheter filter is enabled or not.
  52. ///</summary>
  53. publicboolEnableFiltering
  54. {
  55. get
  56. {
  57. returnConvert.ToBoolean(hdnEnableFiltering.Value);
  58. }
  59. set
  60. {
  61. hdnEnableFiltering.Value = Convert.ToString(value);
  62. }
  63. }
  64. ///<summary>
  65. /// Set the Width of the Combo
  66. ///</summary>
  67. publicstringButtonWidth
  68. {
  69. get
  70. {
  71. returnhdnButtonWidth.Value;
  72. }
  73. set
  74. {
  75. hdnButtonWidth.Value = value;
  76. lblSelectedItems.Style.Add("width", hdnButtonWidth.Value);
  77. }
  78. }
  79. ///<summary>
  80. /// Get Or Set the value to disable dropdownlist when it is empty.
  81. ///</summary>
  82. publicboolDisableIfEmpty
  83. {
  84. get
  85. {
  86. returnConvert.ToBoolean(hdnDisableIfEmpty.Value);
  87. }
  88. set
  89. {
  90. hdnDisableIfEmpty.Value = Convert.ToString(value);
  91. }
  92. }
  93. ///<summary>
  94. /// Get Or Set the value the maximum height for the control.
  95. ///</summary>
  96. publicintMaxHeight
  97. {
  98. get
  99. {
  100. returnConvert.ToInt32(hdnMaxHeight.Value);
  101. }
  102. set
  103. {
  104. hdnMaxHeight.Value = Convert.ToString(value);
  105. }
  106. }
  107. ///<summary>
  108. /// Get Or Set the value for select all option.
  109. ///</summary>
  110. publicstringSelectAllText
  111. {
  112. get
  113. {
  114. returnhdnSelectAllText.Value;
  115. }
  116. set
  117. {
  118. hdnSelectAllText.Value = value;
  119. }
  120. }
  121. ///<summary>
  122. /// Get Or Set the value whether select all option should be there or not.
  123. ///</summary>
  124. publicboolEnableFilteringIgnoreCase
  125. {
  126. get
  127. {
  128. returnConvert.ToBoolean(hdnEnableFilteringIgnoreCase.Value);
  129. }
  130. set
  131. {
  132. hdnEnableFilteringIgnoreCase.Value = Convert.ToString(value);
  133. }
  134. }
  135. publicstringFilterPlaceholder
  136. {
  137. get
  138. {
  139. returnhdnFilterPlaceholder.Value;
  140. }
  141. set
  142. {
  143. hdnFilterPlaceholder.Value = value;
  144. }
  145. }
  146. #endregion
  147. #regionListView Properties
  148. publicstringGetID
  149. {
  150. get
  151. {
  152. returnthis.ID;
  153. }
  154. }
  155. publicstringGetClientID
  156. {
  157. get
  158. {
  159. returnthis.ClientID + "_ddlAutoCompleteSelect";
  160. }
  161. }
  162. ///<summary>
  163. ///To set text search enabled
  164. ///</summary>
  165. publicbool Enabled
  166. {
  167. get
  168. {
  169. returnddlAutoCompleteSelect.Enabled;
  170. }
  171. set
  172. {
  173. ddlAutoCompleteSelect.Enabled = value;
  174. }
  175. }
  176. ///<summary>
  177. ///Sets the Type of DropDownlist it is. For e.g. whether single select or multi select.
  178. ///</summary>
  179. publicListSelectionModeSelectionMode
  180. {
  181. get
  182. {
  183. returnddlAutoCompleteSelect.SelectionMode;
  184. }
  185. set
  186. {
  187. if (value == ListSelectionMode.Single)
  188. {
  189. ddlAutoCompleteSelect.SelectionMode = ListSelectionMode.Single;
  190. hdnSelectionMode.Value = "radio";
  191. }
  192. else
  193. {
  194. ddlAutoCompleteSelect.SelectionMode = ListSelectionMode.Multiple;
  195. hdnSelectionMode.Value = "checkbox";
  196. }
  197. }
  198. }
  199. ///<summary>
  200. ///To set Data Source for Control
  201. ///</summary>
  202. publicList < SelectModel > DataSource
  203. {
  204. set
  205. {
  206. ddlAutoCompleteSelect.DataSource = value;
  207. ddlAutoCompleteSelect.DataBind();
  208. }
  209. }
  210. ///<summary>
  211. ///To set Text field
  212. ///</summary>
  213. publicstringDataTextField
  214. {
  215. get
  216. {
  217. returnddlAutoCompleteSelect.DataTextField;
  218. }
  219. //If String.IsNullOrEmpty(value) Then
  220. // value = _dataTextField
  221. //End If
  222. set
  223. {
  224. ddlAutoCompleteSelect.DataTextField = _dataTextField;
  225. }
  226. }
  227. ///<summary>
  228. ///To set Value field
  229. ///</summary>
  230. publicstringDataValueField
  231. {
  232. get
  233. {
  234. returnddlAutoCompleteSelect.DataValueField;
  235. }
  236. //If String.IsNullOrEmpty(value) Then
  237. // value = _dataValueField
  238. //End If
  239. set
  240. {
  241. ddlAutoCompleteSelect.DataValueField = _dataValueField;
  242. }
  243. }
  244. ///<summary>
  245. /// Get the value of the Selected Items from the dropdownlist.
  246. ///</summary>
  247. publicstring Value
  248. {
  249. get
  250. {
  251. returnhdnValue.Value;
  252. }
  253. }
  254. ///<summary>
  255. /// Get the text of the Selected Items from the dropdownlist.
  256. ///</summary>
  257. publicstring Text
  258. {
  259. get
  260. {
  261. returnhdnText.Value;
  262. }
  263. }
  264. ///<summary>
  265. ///This property is used for setting the auto postback property of the control.
  266. ///</summary>
  267. publicboolAutoPostBack
  268. {
  269. get
  270. {
  271. returnddlAutoCompleteSelect.AutoPostBack;
  272. }
  273. set
  274. {
  275. ddlAutoCompleteSelect.AutoPostBack = value;
  276. }
  277. }
  278. ///<summary>
  279. /// Returns the list of dropdownlist items.
  280. ///</summary>
  281. publicListItemCollection Items
  282. {
  283. get
  284. {
  285. returnddlAutoCompleteSelect.Items;
  286. }
  287. }
  288. ///<summary>
  289. ///Gets Or Sets the selected Index of the dropdownlist.
  290. ///</summary>
  291. publicintSelectedIndex
  292. {
  293. get
  294. {
  295. returnddlAutoCompleteSelect.SelectedIndex;
  296. }
  297. set
  298. {
  299. ddlAutoCompleteSelect.SelectedIndex = value;
  300. }
  301. }
  302. publicListItemSelectedItem
  303. {
  304. get
  305. {
  306. returnddlAutoCompleteSelect.SelectedItem;
  307. }
  308. }
  309. ///<summary>
  310. /// Get Or Sets the selected value of the dropdownlist.
  311. ///</summary>
  312. publicstringSelectedValue
  313. {
  314. get
  315. {
  316. returnddlAutoCompleteSelect.SelectedValue;
  317. }
  318. set
  319. {
  320. if ((ddlAutoCompleteSelect.Items.Count > 0 && !value.Equals("0") && !value.Equals("")))
  321. {
  322. ddlAutoCompleteSelect.SelectedValue = value;
  323. }
  324. }
  325. }
  326. ///<summary>
  327. /// Get Or Sets the error Message to the requiredFieldValidator.
  328. ///</summary>
  329. publicstringErrorMessage
  330. {
  331. get
  332. {
  333. returnreqddlAutoCompleteSelect.ErrorMessage;
  334. }
  335. set
  336. {
  337. reqddlAutoCompleteSelect.ErrorMessage = value;
  338. }
  339. }
  340. publicboolEnableValidation
  341. {
  342. get
  343. {
  344. returnddlAutoCompleteSelect.CausesValidation;
  345. }
  346. set
  347. {
  348. reqddlAutoCompleteSelect.Enabled = value;
  349. ddlAutoCompleteSelect.CausesValidation = value;
  350. }
  351. }
  352. publicstringRequiredFieldValidationGroup
  353. {
  354. get
  355. {
  356. returnreqddlAutoCompleteSelect.ValidationGroup;
  357. }
  358. set
  359. {
  360. reqddlAutoCompleteSelect.ValidationGroup = value;
  361. }
  362. }
  363. publicstringDropDownValidationGroup
  364. {
  365. get
  366. {
  367. returnddlAutoCompleteSelect.ValidationGroup;
  368. }
  369. set
  370. {
  371. ddlAutoCompleteSelect.ValidationGroup = value;
  372. }
  373. }
  374. #endregion
  375. #endregion
  376. #region Page Events
  377. protectedvoidPage_Load(object sender, System.EventArgs e)
  378. {
  379. try
  380. {
  381. if (!(string.IsNullOrEmpty(hdnText.Value) && string.IsNullOrEmpty(hdnValue.Value)))
  382. {
  383. string[] selectedItemsText = hdnText.Value.Split(newchar[]
  384. {
  385. ','
  386. }, StringSplitOptions.RemoveEmptyEntries);
  387. string[] selectedItemsValue = hdnValue.Value.Split(newchar[]
  388. {
  389. ','
  390. }, StringSplitOptions.RemoveEmptyEntries);
  391. IEnumerable < ListItem > listItems = ddlAutoCompleteSelect.Items.Cast < ListItem > ().Where(x => selectedItemsText.Contains(x.Text) && selectedItemsValue.Contains(x.Value));
  392. foreach(ListItem item inlistItems)
  393. {
  394. item.Selected = true;
  395. }
  396. }
  397. }
  398. catch (Exception ex)
  399. {
  400. throw ex;
  401. }
  402. }
  403. protectedvoidPage_PreRender(object sender, System.EventArgs e)
  404. {
  405. try
  406. {
  407. //Registering the scripts file used by the user control. Alternatively you can also set these files inside your master page or the web page on which you are going to use it.
  408. ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "bootStrapJs", ResolveUrl("~/Scripts/bootstrap.min.js"));
  409. ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "bootStrapMultiSelectJs", ResolveUrl("~/Scripts/bootstrap-multiselect.js"));
  410. ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "autoCompleteDdlJs", ResolveUrl("~/Scripts/app/AutoCompleteDdl.js"));
  411. }
  412. catch (Exception ex)
  413. {
  414. throw ex;
  415. }
  416. }
  417. protectedvoid ddlAutoCompleteSelect_SelectedIndexChanged1(object sender, EventArgs e)
  418. {
  419. if (SelectedIndexChanged != null)
  420. {
  421. SelectedIndexChanged(sender, e);
  422. }
  423. }
  424. #endregion
  425. }

AutoCompleteDdl.js

  1. /*Global Variables Declaration*/
  2. //Property Controls
  3. varhdnButtonWidth = '';
  4. varhdnNonSelectedText = '';
  5. varhdnIncludeSelectAllOption = '';
  6. varhdnSelectAllText = '';
  7. varhdnEnableFiltering = '';
  8. varhdnEnableFilteringIgnoreCase = '';
  9. varhdnDisableIfEmpty = '';
  10. varhdnMaxHeight = '';
  11. varhdnFilterPlaceholder = '';
  12. varhdnAllSelectedText = '';
  13. varhdnSelectionMode = '';
  14. //For getting the postBack element ID
  15. varpostBackElementID = '';
  16. //User Control Specific Controls
  17. varlabelId = '';
  18. varhdnTextId = '';
  19. varhdnValueId = '';
  20. varucParentDiv = '';
  21. //Helper variables
  22. varselectedItemsText = '';
  23. varselectedItemsValue = '';
  24. /*This function is used for converting string
  25. "true" or "false" values to Javascript Boolean values.*/
  26. functionconvertToBoolean(value)
  27. {
  28. return (value === "true");
  29. }
  30. functionpageLoad()
  31. {
  32. $(document).ready(function()
  33. {
  34. Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(InitializeRequestHandler);
  35. functionInitializeRequestHandler(sender, args)
  36. {
  37. postBackElementID = args.get_postBackElement().id;
  38. }
  39. //getting the prototype of bootstrap MultiSelect Function/Constructor.
  40. varmultiSelectFunction = $.fn.multiselect.Constructor;
  41. //overriding the UpdateButtonText function of bootstrap MultiSelect Function/Constructor.
  42. multiSelectFunction.prototype.updateButtonText = function() {
  43. //resetting the variable values to ''
  44. selectedItemsText = '';
  45. selectedItemsValue = '';
  46. //retrieving the selected options
  47. var options = this.getSelected();
  48. varinputType = this.options.multiple ? "checkbox" : "radio";
  49. // resetting the updateButtonText event values
  50. if (this.options.enableHTML)
  51. {
  52. $('.multiselect .multiselect-selected-text', this.$container).html(hdnNonSelectedText);
  53. }
  54. else
  55. {
  56. $('.multiselect .multiselect-selected-text', this.$container).text(hdnNonSelectedText);
  57. }
  58. //retrieving the container parent element i.e. User Control's Parent Div
  59. ucParentDiv = this.$container.parent();
  60. //Setting the title attribute of the MultiSelect Button ToNonSelectedText value.
  61. $('.multiselect', this.$container).attr('title', hdnNonSelectedText);
  62. //Setting the label value Or ButtonTextvalue(incase of RadioButton) only if the selectedOption Length > 0
  63. if (options.length > 0)
  64. {
  65. if (inputType === "checkbox")
  66. {
  67. varliSelectedItems = this.options.buttonText(options, this.$select);
  68. //Finding elements for that specific user control scope(if multiple instances of the same UC exists on the page)
  69. labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");
  70. hdnTextId = $(ucParentDiv).find("[id*='hdnText']");
  71. hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");
  72. //Setting the display CSS property value to ""
  73. $(labelId).css("display", "");
  74. //setting the Label data by forming a unordered list.
  75. $(labelId).html("<ul>" + liSelectedItems + "</ul>");
  76. //iterating over the selected options and appending it to the variables if the inputType is "checkbox"
  77. $.each(options, function(index, option)
  78. {
  79. selectedItemsText += option.text + ",";
  80. selectedItemsValue += option.value + ",";
  81. });
  82. //removing the last comma from the string value.
  83. selectedItemsText = selectedItemsText.substring(0, selectedItemsText.lastIndexOf(","));
  84. selectedItemsValue = selectedItemsValue.substring(0, selectedItemsValue.lastIndexOf(","));
  85. }
  86. else
  87. {
  88. //Retrieving the selectedOption from the DropDownList. Here we can simply get the text of the SelectedItem by using options.text() function but, it is a standard followed by
  89. //Bootstrap Multiselect to call the buttonText function and get the selected Item Text.
  90. varselectedOption = this.options.buttonText(options, this.$select);
  91. //setting the selected value on Button Title when the SelectionMode is Single.
  92. if (this.options.enableHTML)
  93. {
  94. $('.multiselect .multiselect-selected-text', this.$container).html(selectedOption);
  95. }
  96. else
  97. {
  98. $('.multiselect .multiselect-selected-text', this.$container).text(selectedOption);
  99. }
  100. $('.multiselect', this.$container).attr('title', selectedOption);
  101. labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");
  102. hdnTextId = $(ucParentDiv).find("[id*='hdnText']");
  103. hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");
  104. //resetting the label value to ""
  105. $(labelId).html("");
  106. //Setting the display css property value to "none".
  107. $(labelId).css("display", "none");
  108. selectedItemsText = options.text();
  109. selectedItemsValue = options.val();
  110. }
  111. }
  112. //finally storing the value to the respective hidden fields.
  113. $(hdnTextId).val(selectedItemsText);
  114. $(hdnValueId).val(selectedItemsValue);
  115. }
  116. //Iterating over each DropdownList on which we need to bind our Bootstrap MultiSelect.
  117. $("select[id*='ddlAutoCompleteSelect']").each(function()
  118. {
  119. varddlCntrl = $(this);
  120. //retrieving the parent element of the dropdownlist control.
  121. vardivUCParent = $(ddlCntrl).parent();
  122. //retrieving the values of the hidden fields/ property values
  123. hdnButtonWidth = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnButtonWidth")).val();
  124. hdnNonSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnNonSelectedText")).val();
  125. hdnIncludeSelectAllOption = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnIncludeSelectAllOption")).val().toString().toLowerCase());
  126. hdnSelectAllText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnSelectAllText")).val();
  127. hdnEnableFiltering = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnEnableFiltering")).val().toString().toLowerCase());
  128. hdnEnableFilteringIgnoreCase = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnEnableFilteringIgnoreCase")).val().toString().toLowerCase());
  129. hdnDisableIfEmpty = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnDisableIfEmpty")).val().toString().toLowerCase());
  130. hdnMaxHeight = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnMaxHeight")).val();
  131. hdnFilterPlaceholder = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnFilterPlaceholder")).val();
  132. hdnAllSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnAllSelectedText")).val();
  133. hdnSelectionMode = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnSelectionMode")).val();
  134. //Retrieving the SelectionMode property value.
  135. varinputType = hdnSelectionMode;
  136. //Applying Bootstrap MultiSelect on DropDownList.
  137. $(this).multiselect({
  138. buttonWidth: hdnButtonWidth,
  139. includeSelectAllOption: hdnIncludeSelectAllOption,
  140. enableFiltering: hdnEnableFiltering,
  141. enableCaseInsensitiveFiltering: hdnEnableFilteringIgnoreCase,
  142. selectAllText: hdnSelectAllText,
  143. nonSelectedText: hdnNonSelectedText,
  144. disableIfEmpty: hdnDisableIfEmpty,
  145. maxHeight: hdnMaxHeight,
  146. filterPlaceholder: hdnFilterPlaceholder,
  147. allSelectedText: hdnAllSelectedText,
  148. buttonText: function(options, select)
  149. {
  150. if (options.length === 0)
  151. {
  152. returnthis.nonSelectedText;
  153. }
  154. else
  155. {
  156. var selected = '';
  157. //For fetching the selected option if the SelectionMode for Dropdownlist is Multiple. i,e. Checkbox.
  158. if (inputType === "checkbox")
  159. {
  160. options.each(function()
  161. {
  162. var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
  163. selected += "<li>" + label + "</li>";
  164. });
  165. }
  166. else
  167. {
  168. //For retrieving the selected option text if the SelectionMode for Dropdownlist is Single. i.e. RadioButton
  169. selected = options.text();
  170. }
  171. return selected;
  172. }
  173. }
  174. });
  175. //For keeping the current dropdownlist open after postback
  176. if (inputType === "checkbox")
  177. {
  178. if (postBackElementID == $(this).attr("id"))
  179. {
  180. //finding the div with class .btn-group
  181. vardivButtonGroup = $("#" + divUCParent.attr("id")).find(".btn-group");
  182. $(divButtonGroup).addClass("open");
  183. }
  184. }
  185. });
  186. });
  187. }
Default.aspx
  1. <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%><%@RegisterSrc="~/UserControl/AutoCompleteDdl.ascx"TagName="AutoCompleteDdl"TagPrefix="uc1"%>
  2. <!DOCTYPEhtml>
  3. <html
  4. xmlns="http://www.w3.org/1999/xhtml">
  5. <headrunatheadrunat="server">
  6. <title>Bootstrap Multiselect</title>
  7. <linkrellinkrel="stylesheet"type="text/css"href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"/>
  8. <linkrellinkrel="stylesheet"type="text/css"href="Style/bootstrap-multiselect.css"/>
  9. <scripttypescripttype="text/javascript"src="Scripts/jquery-1.9.1.min.js">
  10. </script>
  11. </head>
  12. <body>
  13. <formidformid="form1"runat="server">
  14. <asp:ScriptManagerIDasp:ScriptManagerID="ScriptManager1"runat="server">
  15. </asp:ScriptManager>
  16. <asp:UpdatePanelIDasp:UpdatePanelID="udpMain"runat="server">
  17. <ContentTemplate>
  18. <divclassdivclass="container">
  19. <divclassdivclass="row">
  20. <divclassdivclass="col-md-12">
  21. <h3>Bootstrap MultiSelectDropdownlist</h3>
  22. <table>
  23. <tbody>
  24. <tr>
  25. <tdcolspantdcolspan="2">
  26. <h4>Single Select Option</h4>
  27. </td>
  28. </tr>
  29. <tr>
  30. <tdvaligntdvalign="top">Select Item:
  31. </td>
  32. <td>
  33. <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlSingleSelect"runat="server"IncludeSelectAllOption="false"
  34. AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"
  35. MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."
  36. SelectionMode="Single"PlaceHolder="Select a Keyword"/>
  37. <p>
  38. <asp:ButtonIDasp:ButtonID="btnSingleSelect"runat="server"Text="Get Data"OnClick="btnSingleSelect_Click"/>
  39. </p>
  40. </td>
  41. </tr>
  42. <tr>
  43. <tdcolspantdcolspan="2">
  44. <asp:LabelIDasp:LabelID="lblSingleSelectData"runat="server"/>
  45. </td>
  46. </tr>
  47. </tbody>
  48. </table>
  49. </div>
  50. </div>
  51. <divclassdivclass="row">
  52. <divclassdivclass="col-md-12">
  53. <table>
  54. <tbody>
  55. <tr>
  56. <tdcolspantdcolspan="2">
  57. <h4>Multi Select WithAutoPostBack</h4>
  58. </td>
  59. </tr>
  60. <tr>
  61. <tdvaligntdvalign="top">Select Item:
  62. </td>
  63. <td>
  64. <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlMultiSelect"runat="server"IncludeSelectAllOption="false"
  65. AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"
  66. MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."
  67. SelectionMode="Multiple"PlaceHolder="Select a Keyword"/>
  68. <p>
  69. <asp:ButtonIDasp:ButtonID="btnMultiSelect"runat="server"Text="Get Data"OnClick="btnMultiSelect_Click"/>
  70. </p>
  71. </td>
  72. </tr>
  73. <tr>
  74. <tdcolspantdcolspan="2">
  75. <asp:LabelIDasp:LabelID="lblMultiSelectData"runat="server"/>
  76. </td>
  77. </tr>
  78. </tbody>
  79. </table>
  80. </div>
  81. </div>
  82. <divclassdivclass="row">
  83. <divclassdivclass="col-md-12">
  84. <table>
  85. <tbody>
  86. <tr>
  87. <tdcolspantdcolspan="2">
  88. <h4>Multi Select With AutoPostback And Dependent DDL</h4>
  89. </td>
  90. </tr>
  91. <tr>
  92. <tdvaligntdvalign="top">Select Item:
  93. </td>
  94. <td>
  95. <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlPrimaryMultiSelect"runat="server"IncludeSelectAllOption="false"
  96. AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"
  97. MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."
  98. SelectionMode="Single"PlaceHolder="Select a Keyword"/>
  99. </td>
  100. </tr>
  101. <tr>
  102. <td>Select Another Item:</td>
  103. <td>
  104. <asp:DropDownListIDasp:DropDownListID="ddlDependent"runat="server"CssClass="dropdown">
  105. </asp:DropDownList>
  106. </td>
  107. </tr>
  108. <tr>
  109. <tdcolspantdcolspan="2">
  110. <asp:LabelIDasp:LabelID="lblMultiPostbckData"runat="server"/>
  111. </td>
  112. </tr>
  113. </tbody>
  114. </table>
  115. </div>
  116. </div>
  117. </div>
  118. </ContentTemplate>
  119. </asp:UpdatePanel>
  120. </form>
  121. </body>
  122. </html>
Default.aspx.cs
  1. using System;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Web.UI;
  6. usingSystem.Web.UI.WebControls;
  7. publicpartialclass_Default: System.Web.UI.Page
  8. {
  9. List < SelectModel > lstData = newList < SelectModel > ();
  10. List < SelectModel > lstDependent = newList < SelectModel > ();
  11. protectedvoidPage_Load(object sender, EventArgs e)
  12. {
  13. if (!IsPostBack)
  14. {
  15. LoadData();
  16. LoadSingleSelectData();
  17. LoadMultiSelectData();
  18. LoadPrimaryMultiSelect();
  19. }
  20. ddlPrimaryMultiSelect.SelectedIndexChanged += ddlPrimaryMultiSelect_SelectedIndexChanged;
  21. }
  22. publicvoidddlPrimaryMultiSelect_SelectedIndexChanged(object sender, EventArgs e) {
  23. LoadDependentDDL();
  24. }
  25. privatevoidLoadData()
  26. {
  27. for (inti = 0; i < 5; i++)
  28. {
  29. lstData.Add(newSelectModel()
  30. {
  31. Value = "Item " + i, Text = "Item " + i
  32. });
  33. }
  34. }
  35. privatevoidLoadSingleSelectData()
  36. {
  37. ddlSingleSelect.DataValueField = "Value";
  38. ddlSingleSelect.DataTextField = "Text";
  39. //Setting the data source for the dropdownlist
  40. ddlSingleSelect.DataSource = lstData;
  41. }
  42. privatevoidLoadMultiSelectData()
  43. {
  44. ddlMultiSelect.DataValueField = "Value";
  45. ddlMultiSelect.DataTextField = "Text";
  46. ddlMultiSelect.DataSource = lstData;
  47. }
  48. privatevoidLoadPrimaryMultiSelect()
  49. {
  50. ddlPrimaryMultiSelect.DataValueField = "Value";
  51. ddlPrimaryMultiSelect.DataTextField = "Text";
  52. ddlPrimaryMultiSelect.DataSource = lstData;
  53. }
  54. privatevoidLoadDependentDDL()
  55. {
  56. stringselectedItem = ddlPrimaryMultiSelect.SelectedItem.Text;
  57. stringsubItem = "Sub " + selectedItem;
  58. lstDependent.Clear();
  59. lstDependent.Add(newSelectModel()
  60. {
  61. Text = subItem, Value = subItem
  62. });
  63. ddlDependent.DataValueField = "Value";
  64. ddlDependent.DataTextField = "Text";
  65. ddlDependent.DataSource = lstDependent;
  66. ddlDependent.DataBind();
  67. }
  68. protectedvoidbtnSingleSelect_Click(object sender, EventArgs e) {
  69. string value = ddlSingleSelect.Value;
  70. string text = ddlSingleSelect.Text;
  71. lblSingleSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;
  72. }
  73. protectedvoidbtnMultiSelect_Click(object sender, EventArgs e)
  74. {
  75. string value = ddlMultiSelect.Value;
  76. string text = ddlMultiSelect.Text;
  77. lblMultiSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;
  78. }
  79. }
Now let’s run the application and you’ll see the following output.


Figure 1: Output