Creating Multiselect DropDownList Control In ASP.NET 4.0 Using Bootstrap: Part 2

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
  • It allows the user to select multiple items from a dropdownlist at a single point of time.
  • By setting a single property we can make the control as “Multi Select” or “Single Select”.
  • We also saw that the control is capable of maintaining its state during postback / server round trips.

Demerits

  • The control is not making full use of JavaScript features such as polymorphism, method overriding, etc.
  • Also it lacks server side properties of dropdownlist like AutoPostBack, ValidationGroup, SelectedIndexChanged event, etc.
  • Did not impose any validation like requiredField validator on the dropdownlist control.
  • UI wise improvement can be done.

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

AutoCompleteDdl.js

  1. /*Global Variables Declaration*/  
  2.   
  3. //Property Controls      
  4. varhdnButtonWidth = '';  
  5. varhdnNonSelectedText = '';  
  6. varhdnIncludeSelectAllOption = '';  
  7. varhdnSelectAllText = '';  
  8. varhdnEnableFiltering = '';  
  9. varhdnEnableFilteringIgnoreCase = '';  
  10. varhdnDisableIfEmpty = '';  
  11. varhdnMaxHeight = '';  
  12. varhdnFilterPlaceholder = '';  
  13. varhdnAllSelectedText = '';  
  14. varhdnSelectionMode = '';  
  15. //For getting the postBack element ID      
  16. varpostBackElementID = '';  
  17.   
  18. //User Control Specific Controls      
  19. varlabelId = '';  
  20. varhdnTextId = '';  
  21. varhdnValueId = '';  
  22. varucParentDiv = '';  
  23.   
  24. //Helper variables      
  25. varselectedItemsText = '';  
  26. varselectedItemsValue = '';  
  27.   
  28. /*This function is used for converting string    
  29. "true" or "false" values to Javascript Boolean values.*/  
  30. functionconvertToBoolean(value)  
  31. {  
  32.     return (value === "true");  
  33. }  
  34.   
  35. functionpageLoad()  
  36. {  
  37.   
  38.     $(document).ready(function()   
  39.     {  
  40.   
  41.         Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(InitializeRequestHandler);  
  42.         functionInitializeRequestHandler(sender, args)  
  43.         {  
  44.             postBackElementID = args.get_postBackElement().id;  
  45.         }  
  46.   
  47.         //getting the prototype of bootstrap MultiSelect Function/Constructor.      
  48.         varmultiSelectFunction = $.fn.multiselect.Constructor;  
  49.   
  50.         //overriding the UpdateButtonText function of bootstrap MultiSelect Function/Constructor.      
  51.         multiSelectFunction.prototype.updateButtonText = function() {  
  52.             //resetting the variable values to ''      
  53.             selectedItemsText = '';  
  54.             selectedItemsValue = '';  
  55.   
  56.             //retrieving the selected options      
  57.             var options = this.getSelected();  
  58.   
  59.             varinputType = this.options.multiple ? "checkbox" : "radio";  
  60.   
  61.             // resetting the updateButtonText event values      
  62.             if (this.options.enableHTML)   
  63.             {  
  64.                 $('.multiselect .multiselect-selected-text'this.$container).html(hdnNonSelectedText);  
  65.             }   
  66.             else   
  67.             {  
  68.                 $('.multiselect .multiselect-selected-text'this.$container).text(hdnNonSelectedText);  
  69.             }  
  70.   
  71.             //retrieving the container parent element i.e. User Control's Parent Div      
  72.             ucParentDiv = this.$container.parent();  
  73.   
  74.             //Setting the title attribute of the MultiSelect Button ToNonSelectedText value.      
  75.             $('.multiselect'this.$container).attr('title', hdnNonSelectedText);  
  76.   
  77.             //Setting the label value Or ButtonTextvalue(incase of RadioButton) only if the selectedOption Length > 0      
  78.             if (options.length > 0)  
  79.             {  
  80.                 if (inputType === "checkbox")  
  81.                 {  
  82.                     varliSelectedItems = this.options.buttonText(options, this.$select);  
  83.   
  84.                     //Finding elements for that specific user control scope(if multiple instances of the same UC exists on the page)      
  85.                     labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");  
  86.                     hdnTextId = $(ucParentDiv).find("[id*='hdnText']");  
  87.                     hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");  
  88.   
  89.                     //Setting the display CSS property value to ""      
  90.                     $(labelId).css("display""");  
  91.                     //setting the Label data by forming a unordered list.      
  92.                     $(labelId).html("<ul>" + liSelectedItems + "</ul>");  
  93.   
  94.                     //iterating over the selected options and appending it to the variables if the inputType is "checkbox"      
  95.                     $.each(options, function(index, option)  
  96.                     {  
  97.                         selectedItemsText += option.text + ",";  
  98.                         selectedItemsValue += option.value + ",";  
  99.                     });  
  100.   
  101.                     //removing the last comma from the string value.      
  102.                     selectedItemsText = selectedItemsText.substring(0, selectedItemsText.lastIndexOf(","));  
  103.                     selectedItemsValue = selectedItemsValue.substring(0, selectedItemsValue.lastIndexOf(","));  
  104.   
  105.                 }   
  106.                 else  
  107.                 {  
  108.                     //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       
  109.                     //Bootstrap Multiselect to call the buttonText function and get the selected Item Text.      
  110.                     varselectedOption = this.options.buttonText(options, this.$select);  
  111.                     //setting the selected value on Button Title when the SelectionMode is Single.      
  112.                     if (this.options.enableHTML)  
  113.                     {  
  114.                         $('.multiselect .multiselect-selected-text'this.$container).html(selectedOption);  
  115.                     }   
  116.                     else   
  117.                     {  
  118.                         $('.multiselect .multiselect-selected-text'this.$container).text(selectedOption);  
  119.                     }  
  120.   
  121.                     $('.multiselect'this.$container).attr('title', selectedOption);  
  122.   
  123.                     labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");  
  124.                     hdnTextId = $(ucParentDiv).find("[id*='hdnText']");  
  125.                     hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");  
  126.   
  127.                     //resetting the label value to ""      
  128.                     $(labelId).html("");  
  129.                     //Setting the display css property value to "none".      
  130.                     $(labelId).css("display""none");  
  131.   
  132.                     selectedItemsText = options.text();  
  133.                     selectedItemsValue = options.val();  
  134.                 }  
  135.             }  
  136.   
  137.             //finally storing the value to the respective hidden fields.      
  138.             $(hdnTextId).val(selectedItemsText);  
  139.             $(hdnValueId).val(selectedItemsValue);  
  140.         }  
  141.   
  142.   
  143.         //Iterating over each DropdownList on which we need to bind our Bootstrap MultiSelect.      
  144.         $("select[id*='ddlAutoCompleteSelect']").each(function()   
  145.         {  
  146.             varddlCntrl = $(this);  
  147.             //retrieving the parent element of the dropdownlist control.      
  148.             vardivUCParent = $(ddlCntrl).parent();  
  149.   
  150.             //retrieving the values of the hidden fields/ property values      
  151.             hdnButtonWidth = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnButtonWidth")).val();  
  152.             hdnNonSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnNonSelectedText")).val();  
  153.             hdnIncludeSelectAllOption = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnIncludeSelectAllOption")).val().toString().toLowerCase());  
  154.             hdnSelectAllText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnSelectAllText")).val();  
  155.             hdnEnableFiltering = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnEnableFiltering")).val().toString().toLowerCase());  
  156.             hdnEnableFilteringIgnoreCase = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnEnableFilteringIgnoreCase")).val().toString().toLowerCase());  
  157.             hdnDisableIfEmpty = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnDisableIfEmpty")).val().toString().toLowerCase());  
  158.             hdnMaxHeight = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnMaxHeight")).val();  
  159.             hdnFilterPlaceholder = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnFilterPlaceholder")).val();  
  160.             hdnAllSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnAllSelectedText")).val();  
  161.             hdnSelectionMode = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect""hdnSelectionMode")).val();  
  162.   
  163.             //Retrieving the SelectionMode property value.      
  164.             varinputType = hdnSelectionMode;  
  165.   
  166.             //Applying Bootstrap MultiSelect on DropDownList.      
  167.             $(this).multiselect({  
  168.                 buttonWidth: hdnButtonWidth,  
  169.                 includeSelectAllOption: hdnIncludeSelectAllOption,  
  170.                 enableFiltering: hdnEnableFiltering,  
  171.                 enableCaseInsensitiveFiltering: hdnEnableFilteringIgnoreCase,  
  172.                 selectAllText: hdnSelectAllText,  
  173.                 nonSelectedText: hdnNonSelectedText,  
  174.                 disableIfEmpty: hdnDisableIfEmpty,  
  175.                 maxHeight: hdnMaxHeight,  
  176.                 filterPlaceholder: hdnFilterPlaceholder,  
  177.                 allSelectedText: hdnAllSelectedText,  
  178.                 buttonText: function(options, select)  
  179.                 {  
  180.                     if (options.length === 0)   
  181.                     {  
  182.                         returnthis.nonSelectedText;  
  183.                     }   
  184.                     else  
  185.                     {  
  186.                         var selected = '';  
  187.                         //For fetching the selected option if the SelectionMode for Dropdownlist is Multiple. i,e. Checkbox.      
  188.                         if (inputType === "checkbox")   
  189.                         {  
  190.                             options.each(function()   
  191.                             {  
  192.                                 var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();  
  193.                                 selected += "<li>" + label + "</li>";  
  194.                             });  
  195.                         }   
  196.                         else   
  197.                         {  
  198.                             //For retrieving the selected option text if the SelectionMode for Dropdownlist is Single. i.e. RadioButton      
  199.                             selected = options.text();  
  200.                         }  
  201.                         return selected;  
  202.                     }  
  203.                 }  
  204.             });  
  205.   
  206.             //For keeping the current dropdownlist open after postback      
  207.             if (inputType === "checkbox")  
  208.             {  
  209.                 if (postBackElementID == $(this).attr("id"))  
  210.                 {  
  211.                     //finding the div with class .btn-group      
  212.                     vardivButtonGroup = $("#" + divUCParent.attr("id")).find(".btn-group");  
  213.                     $(divButtonGroup).addClass("open");  
  214.                 }  
  215.             }  
  216.         });  
  217.     });  
  218. }  
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.   
  8. publicpartialclass_Default: System.Web.UI.Page   
  9. {  
  10.     List < SelectModel > lstData = newList < SelectModel > ();  
  11.     List < SelectModel > lstDependent = newList < SelectModel > ();  
  12.   
  13.     protectedvoidPage_Load(object sender, EventArgs e)   
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             LoadData();  
  18.             LoadSingleSelectData();  
  19.             LoadMultiSelectData();  
  20.             LoadPrimaryMultiSelect();  
  21.         }  
  22.         ddlPrimaryMultiSelect.SelectedIndexChanged += ddlPrimaryMultiSelect_SelectedIndexChanged;  
  23.     }  
  24.   
  25.     publicvoidddlPrimaryMultiSelect_SelectedIndexChanged(object sender, EventArgs e) {  
  26.         LoadDependentDDL();  
  27.     }  
  28.   
  29.     privatevoidLoadData()   
  30.     {  
  31.         for (inti = 0; i < 5; i++)   
  32.         {  
  33.             lstData.Add(newSelectModel()  
  34.             {  
  35.                 Value = "Item " + i, Text = "Item " + i  
  36.             });  
  37.         }  
  38.     }  
  39.   
  40.     privatevoidLoadSingleSelectData()  
  41.     {  
  42.         ddlSingleSelect.DataValueField = "Value";  
  43.         ddlSingleSelect.DataTextField = "Text";  
  44.         //Setting the data source for the dropdownlist    
  45.         ddlSingleSelect.DataSource = lstData;  
  46.     }  
  47.   
  48.     privatevoidLoadMultiSelectData()   
  49.     {  
  50.         ddlMultiSelect.DataValueField = "Value";  
  51.         ddlMultiSelect.DataTextField = "Text";  
  52.         ddlMultiSelect.DataSource = lstData;  
  53.     }  
  54.   
  55.     privatevoidLoadPrimaryMultiSelect()   
  56.     {  
  57.         ddlPrimaryMultiSelect.DataValueField = "Value";  
  58.         ddlPrimaryMultiSelect.DataTextField = "Text";  
  59.         ddlPrimaryMultiSelect.DataSource = lstData;  
  60.     }  
  61.   
  62.     privatevoidLoadDependentDDL()  
  63.     {  
  64.         stringselectedItem = ddlPrimaryMultiSelect.SelectedItem.Text;  
  65.         stringsubItem = "Sub " + selectedItem;  
  66.         lstDependent.Clear();  
  67.         lstDependent.Add(newSelectModel()   
  68.         {  
  69.             Text = subItem, Value = subItem  
  70.         });  
  71.         ddlDependent.DataValueField = "Value";  
  72.         ddlDependent.DataTextField = "Text";  
  73.         ddlDependent.DataSource = lstDependent;  
  74.         ddlDependent.DataBind();  
  75.     }  
  76.   
  77.     protectedvoidbtnSingleSelect_Click(object sender, EventArgs e) {  
  78.         string value = ddlSingleSelect.Value;  
  79.         string text = ddlSingleSelect.Text;  
  80.   
  81.         lblSingleSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;  
  82.     }  
  83.   
  84.     protectedvoidbtnMultiSelect_Click(object sender, EventArgs e)   
  85.     {  
  86.         string value = ddlMultiSelect.Value;  
  87.         string text = ddlMultiSelect.Text;  
  88.   
  89.         lblMultiSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;  
  90.     }  
  91.   
Now let’s run the application and you’ll see the following output.


Figure 1: Output


Similar Articles