"> کار با DropDownList در ASP.NET 4.0 با استفاده از Bootstrap قسمت دوم | ام اس پی سافت

کار با DropDownList در ASP.NET 4.0 با استفاده از Bootstrap قسمت دوم

DropDownList

در این مقاله با هم خواهیم آموخت که چگونه میتوان یک کنترل چند انتخابی DropDownList در ASP.NET 4.0 با استفاده از Bootstrap ایجاد کرد. فواید و معایب این DropDownList به همراه کد های کامل در ادامه ی مطلب برایتان قرار داده شده است …

DropDownList

فواید

به کاربر اجازه می دهد که از یک dropdownlist انتخاب چندگانه داشته باشد.

با تنظیم کردن یک ویژگی می توانیم از حالت انتخاب چندگانه (Multi Select) به حالت تکی (Single Select) برویم.

هم چنین می بینیم که کنترل آن، و نگهداری حالت خود در طول postback و server round trips ثابت است.

معایب

کنترل، اجازه استفاده کامل از ویژگی های JavaScript مانند: polymorphism، method overriding و… را نمی دهد.

هم چنین فاقد properties سرور dropdownlist مانند: AutoPostBack، ValidationGroup، ValidationGroup و… می باشد.

هیچ اعتباری را مثل: requiredField validator در کنترل dropdownlist اعمال نمی کند.

در این مقاله هموراه سعی در بهبود کنترل کاربری خود داریم که بنوانیم مشکلات را حل کنیم.

AutoCompleteDdl.aspx code

<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="AutoCompleteDdl.ascx.cs"Inherits="User_Control_AutoCompleteDdl"%>  
<divstyledivstyledivstyledivstyledivstyledivstyledivstyledivstyle="width: 380px;"id="divAutoComplete"runat="server">  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnButtonWidth"runat="server"Value="320px"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnNonSelectedText"runat="server"Value="--Select--"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnIncludeSelectAllOption"runat="server"Value="false"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnSelectAllText"runat="server"Value="All"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnEnableFiltering"runat="server"Value="False"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnEnableFilteringIgnoreCase"runat="server"Value="False"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnDisableIfEmpty"runat="server"Value="False"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnMaxHeight"runat="server"Value="200"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnFilterPlaceholder"runat="server"Value="Search for something..."/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnAllSelectedText"runat="server"Value="No option left..."/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnText"runat="server"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnValue"runat="server"/>  
    <asp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldIDasp:HiddenFieldID="hdnSelectionMode"runat="server"Value="checkbox"/>  
    <asp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxIDasp:ListBoxID="ddlAutoCompleteSelect"runat="server"Style="width: 350px;"      
SelectionMode="Multiple"OnSelectedIndexChanged="ddlAutoCompleteSelect_SelectedIndexChanged1">  
    </asp:ListBox>  
    <!--Adding RequiredField Validator-->  
    <asp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorIDasp:RequiredFieldValidatorID="reqddlAutoCompleteSelect"runat="server"ControlToValidate="ddlAutoCompleteSelect"      
InitialValue=""Display="Dynamic"Enabled="False"ForeColor="Red">  
    </asp:RequiredFieldValidator>  
    <p>  
        <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;">  
        </asp:Label>  
    </p>  
</div>  

AutoCompleteDdl.aspx.cs

using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Web;  
usingSystem.Web.UI;  
usingSystem.Web.UI.WebControls;  
  
publicpartialclassUser_Control_AutoCompleteDdl: System.Web.UI.UserControl {#region Variable Declarations  
  
    privateconststring _dataTextField = "Text";  
    privateconststring _dataValueField = "Value";  
    publiceventEventHandlerSelectedIndexChanged;  
 
    #endregion  
 
    #region Properties  
 
    #regionBootStrap Properties  
  
    ///<summary>    
    ///Set the placeholder for the DropDownlist.    
    ///</summary>    
    publicstringNonSelectedText   
    {  
        get   
        {  
            returnhdnNonSelectedText.Value;  
        }  
        set   
        {  
            hdnNonSelectedText.Value = value;  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value whether select all option should be included or not.    
    ///</summary>    
    publicboolIncludeSelectAllOption   
    {  
        get   
        {  
            returnConvert.ToBoolean(hdnIncludeSelectAllOption.Value);  
        }  
        set   
        {  
            //For radio Button or Single Select there is no need of including the selectAll Option/checkBox button.     
            //That's why the default value of "false" is set even if the value is "True".    
            if (value == true && SelectionMode == ListSelectionMode.Single) {  
                hdnIncludeSelectAllOption.Value = "false";  
            }   
            else   
            {  
                hdnIncludeSelectAllOption.Value = Convert.ToString(value);  
            }  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value wheter filter is enabled or not.    
    ///</summary>    
    publicboolEnableFiltering   
    {  
        get   
        {  
            returnConvert.ToBoolean(hdnEnableFiltering.Value);  
        }  
        set   
        {  
            hdnEnableFiltering.Value = Convert.ToString(value);  
        }  
    }  
  
    ///<summary>    
    /// Set the Width of the Combo    
    ///</summary>    
    publicstringButtonWidth   
    {  
        get   
        {  
            returnhdnButtonWidth.Value;  
        }  
        set   
        {  
            hdnButtonWidth.Value = value;  
            lblSelectedItems.Style.Add("width", hdnButtonWidth.Value);  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value to disable dropdownlist when it is empty.    
    ///</summary>    
    publicboolDisableIfEmpty   
    {  
        get   
        {  
            returnConvert.ToBoolean(hdnDisableIfEmpty.Value);  
        }  
        set   
        {  
            hdnDisableIfEmpty.Value = Convert.ToString(value);  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value the maximum height for the control.    
    ///</summary>    
    publicintMaxHeight   
    {  
        get  
        {  
            returnConvert.ToInt32(hdnMaxHeight.Value);  
        }  
        set   
        {  
            hdnMaxHeight.Value = Convert.ToString(value);  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value for select all option.    
    ///</summary>    
    publicstringSelectAllText   
    {  
        get   
        {  
            returnhdnSelectAllText.Value;  
        }  
        set   
        {  
            hdnSelectAllText.Value = value;  
        }  
    }  
  
    ///<summary>    
    /// Get Or Set the value whether select all option should be there or not.    
    ///</summary>    
    publicboolEnableFilteringIgnoreCase   
    {  
        get   
        {  
            returnConvert.ToBoolean(hdnEnableFilteringIgnoreCase.Value);  
        }  
        set   
        {  
            hdnEnableFilteringIgnoreCase.Value = Convert.ToString(value);  
        }  
    }  
  
    publicstringFilterPlaceholder   
    {  
        get   
        {  
            returnhdnFilterPlaceholder.Value;  
        }  
        set   
        {  
            hdnFilterPlaceholder.Value = value;  
        }  
    }  
 
 
    #endregion  
 
    #regionListView Properties  
  
    publicstringGetID   
    {  
        get   
        {  
            returnthis.ID;  
        }  
    }  
  
    publicstringGetClientID  
    {  
        get   
        {  
            returnthis.ClientID + "_ddlAutoCompleteSelect";  
        }  
    }  
  
    ///<summary>    
    ///To set text search enabled    
    ///</summary>    
    publicbool Enabled   
    {  
        get  
        {  
            returnddlAutoCompleteSelect.Enabled;  
        }  
        set   
        {  
            ddlAutoCompleteSelect.Enabled = value;  
        }  
    }  
  
    ///<summary>    
    ///Sets the Type of DropDownlist it is. For e.g. whether single select or multi select.    
    ///</summary>    
    publicListSelectionModeSelectionMode   
    {  
        get  
        {  
            returnddlAutoCompleteSelect.SelectionMode;  
        }  
        set   
        {  
            if (value == ListSelectionMode.Single)   
            {  
                ddlAutoCompleteSelect.SelectionMode = ListSelectionMode.Single;  
                hdnSelectionMode.Value = "radio";  
            }   
            else   
            {  
                ddlAutoCompleteSelect.SelectionMode = ListSelectionMode.Multiple;  
                hdnSelectionMode.Value = "checkbox";  
            }  
        }  
    }  
  
    ///<summary>    
    ///To set Data Source for Control    
    ///</summary>    
    publicList < SelectModel > DataSource  
    {  
        set   
        {  
            ddlAutoCompleteSelect.DataSource = value;  
            ddlAutoCompleteSelect.DataBind();  
        }  
    }  
  
    ///<summary>    
    ///To set Text field    
    ///</summary>    
    publicstringDataTextField  
    {  
        get  
        {  
            returnddlAutoCompleteSelect.DataTextField;  
        }  
        //If String.IsNullOrEmpty(value) Then    
        //    value = _dataTextField    
        //End If    
        set   
        {  
            ddlAutoCompleteSelect.DataTextField = _dataTextField;  
        }  
    }  
  
    ///<summary>    
    ///To set Value field    
    ///</summary>    
    publicstringDataValueField  
    {  
        get   
        {  
            returnddlAutoCompleteSelect.DataValueField;  
        }  
        //If String.IsNullOrEmpty(value) Then    
        //    value = _dataValueField    
        //End If    
        set   
        {  
            ddlAutoCompleteSelect.DataValueField = _dataValueField;  
        }  
    }  
  
    ///<summary>    
    /// Get the value of the Selected Items from the dropdownlist.    
    ///</summary>    
    publicstring Value  
    {  
        get   
        {  
            returnhdnValue.Value;  
        }  
    }  
  
    ///<summary>    
    /// Get the text of the Selected Items from the dropdownlist.    
    ///</summary>    
    publicstring Text  
    {  
        get  
        {  
            returnhdnText.Value;  
        }  
    }  
  
    ///<summary>    
    ///This property is used for setting the auto postback property of the control.    
    ///</summary>    
    publicboolAutoPostBack   
    {  
        get   
        {  
            returnddlAutoCompleteSelect.AutoPostBack;  
        }  
        set   
        {  
            ddlAutoCompleteSelect.AutoPostBack = value;  
        }  
    }  
  
    ///<summary>    
    /// Returns the list of dropdownlist items.    
    ///</summary>    
    publicListItemCollection Items   
    {  
        get   
        {  
            returnddlAutoCompleteSelect.Items;  
        }  
    }  
  
    ///<summary>    
    ///Gets Or Sets the selected Index of the dropdownlist.    
    ///</summary>    
    publicintSelectedIndex   
    {  
        get   
        {  
            returnddlAutoCompleteSelect.SelectedIndex;  
        }  
        set  
        {  
            ddlAutoCompleteSelect.SelectedIndex = value;  
        }  
    }  
  
    publicListItemSelectedItem   
    {  
        get   
        {  
            returnddlAutoCompleteSelect.SelectedItem;  
        }  
    }  
    ///<summary>    
    /// Get Or Sets the selected value of the dropdownlist.    
    ///</summary>    
    publicstringSelectedValue  
    {  
        get  
        {  
            returnddlAutoCompleteSelect.SelectedValue;  
        }  
        set  
        {  
            if ((ddlAutoCompleteSelect.Items.Count > 0 && !value.Equals("0") && !value.Equals("")))   
            {  
                ddlAutoCompleteSelect.SelectedValue = value;  
            }  
        }  
    }  
  
    ///<summary>    
    /// Get Or Sets the error Message to the requiredFieldValidator.    
    ///</summary>    
    publicstringErrorMessage   
    {  
        get   
        {  
            returnreqddlAutoCompleteSelect.ErrorMessage;  
        }  
        set  
        {  
            reqddlAutoCompleteSelect.ErrorMessage = value;  
        }  
    }  
  
    publicboolEnableValidation   
    {  
        get   
        {  
            returnddlAutoCompleteSelect.CausesValidation;  
        }  
        set  
        {  
            reqddlAutoCompleteSelect.Enabled = value;  
            ddlAutoCompleteSelect.CausesValidation = value;  
        }  
    }  
  
    publicstringRequiredFieldValidationGroup   
    {  
        get   
        {  
            returnreqddlAutoCompleteSelect.ValidationGroup;  
        }  
  
        set  
        {  
            reqddlAutoCompleteSelect.ValidationGroup = value;  
        }  
    }  
  
    publicstringDropDownValidationGroup  
    {  
        get  
        {  
            returnddlAutoCompleteSelect.ValidationGroup;  
        }  
        set   
        {  
            ddlAutoCompleteSelect.ValidationGroup = value;  
        }  
    }  
 
    #endregion  
 
    #endregion  
 
    #region Page Events  
  
    protectedvoidPage_Load(object sender, System.EventArgs e)   
    {  
        try  
        {  
            if (!(string.IsNullOrEmpty(hdnText.Value) && string.IsNullOrEmpty(hdnValue.Value)))   
            {  
                string[] selectedItemsText = hdnText.Value.Split(newchar[]  
                {  
                    ','  
                }, StringSplitOptions.RemoveEmptyEntries);  
                string[] selectedItemsValue = hdnValue.Value.Split(newchar[]  
                {  
                    ','  
                }, StringSplitOptions.RemoveEmptyEntries);  
  
                IEnumerable < ListItem > listItems = ddlAutoCompleteSelect.Items.Cast < ListItem > ().Where(x => selectedItemsText.Contains(x.Text) && selectedItemsValue.Contains(x.Value));  
  
                foreach(ListItem item inlistItems)   
                {  
                    item.Selected = true;  
                }  
            }  
        }   
        catch (Exception ex)  
        {  
            throw ex;  
        }  
    }  
  
    protectedvoidPage_PreRender(object sender, System.EventArgs e)   
    {  
        try   
        {  
            //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.      
            ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "bootStrapJs", ResolveUrl("~/Scripts/bootstrap.min.js"));  
            ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "bootStrapMultiSelectJs", ResolveUrl("~/Scripts/bootstrap-multiselect.js"));  
            ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "autoCompleteDdlJs", ResolveUrl("~/Scripts/app/AutoCompleteDdl.js"));  
        }   
        catch (Exception ex)   
        {  
            throw ex;  
        }  
    }  
  
    protectedvoid ddlAutoCompleteSelect_SelectedIndexChanged1(object sender, EventArgs e)   
    {  
        if (SelectedIndexChanged != null)  
        {  
            SelectedIndexChanged(sender, e);  
        }  
    }  
 
    #endregion  
  
} 

AutoCompleteDdl.js

/*Global Variables Declaration*/  
  
//Property Controls      
varhdnButtonWidth = '';  
varhdnNonSelectedText = '';  
varhdnIncludeSelectAllOption = '';  
varhdnSelectAllText = '';  
varhdnEnableFiltering = '';  
varhdnEnableFilteringIgnoreCase = '';  
varhdnDisableIfEmpty = '';  
varhdnMaxHeight = '';  
varhdnFilterPlaceholder = '';  
varhdnAllSelectedText = '';  
varhdnSelectionMode = '';  
//For getting the postBack element ID      
varpostBackElementID = '';  
  
//User Control Specific Controls      
varlabelId = '';  
varhdnTextId = '';  
varhdnValueId = '';  
varucParentDiv = '';  
  
//Helper variables      
varselectedItemsText = '';  
varselectedItemsValue = '';  
  
/*This function is used for converting string    
"true" or "false" values to Javascript Boolean values.*/  
functionconvertToBoolean(value)  
{  
    return (value === "true");  
}  
  
functionpageLoad()  
{  
  
    $(document).ready(function()   
    {  
  
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(InitializeRequestHandler);  
        functionInitializeRequestHandler(sender, args)  
        {  
            postBackElementID = args.get_postBackElement().id;  
        }  
  
        //getting the prototype of bootstrap MultiSelect Function/Constructor.      
        varmultiSelectFunction = $.fn.multiselect.Constructor;  
  
        //overriding the UpdateButtonText function of bootstrap MultiSelect Function/Constructor.      
        multiSelectFunction.prototype.updateButtonText = function() {  
            //resetting the variable values to ''      
            selectedItemsText = '';  
            selectedItemsValue = '';  
  
            //retrieving the selected options      
            var options = this.getSelected();  
  
            varinputType = this.options.multiple ? "checkbox" : "radio";  
  
            // resetting the updateButtonText event values      
            if (this.options.enableHTML)   
            {  
                $('.multiselect .multiselect-selected-text', this.$container).html(hdnNonSelectedText);  
            }   
            else   
            {  
                $('.multiselect .multiselect-selected-text', this.$container).text(hdnNonSelectedText);  
            }  
  
            //retrieving the container parent element i.e. User Control's Parent Div      
            ucParentDiv = this.$container.parent();  
  
            //Setting the title attribute of the MultiSelect Button ToNonSelectedText value.      
            $('.multiselect', this.$container).attr('title', hdnNonSelectedText);  
  
            //Setting the label value Or ButtonTextvalue(incase of RadioButton) only if the selectedOption Length > 0      
            if (options.length > 0)  
            {  
                if (inputType === "checkbox")  
                {  
                    varliSelectedItems = this.options.buttonText(options, this.$select);  
  
                    //Finding elements for that specific user control scope(if multiple instances of the same UC exists on the page)      
                    labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");  
                    hdnTextId = $(ucParentDiv).find("[id*='hdnText']");  
                    hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");  
  
                    //Setting the display CSS property value to ""      
                    $(labelId).css("display", "");  
                    //setting the Label data by forming a unordered list.      
                    $(labelId).html("<ul>" + liSelectedItems + "</ul>");  
  
                    //iterating over the selected options and appending it to the variables if the inputType is "checkbox"      
                    $.each(options, function(index, option)  
                    {  
                        selectedItemsText += option.text + ",";  
                        selectedItemsValue += option.value + ",";  
                    });  
  
                    //removing the last comma from the string value.      
                    selectedItemsText = selectedItemsText.substring(0, selectedItemsText.lastIndexOf(","));  
                    selectedItemsValue = selectedItemsValue.substring(0, selectedItemsValue.lastIndexOf(","));  
  
                }   
                else  
                {  
                    //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       
                    //Bootstrap Multiselect to call the buttonText function and get the selected Item Text.      
                    varselectedOption = this.options.buttonText(options, this.$select);  
                    //setting the selected value on Button Title when the SelectionMode is Single.      
                    if (this.options.enableHTML)  
                    {  
                        $('.multiselect .multiselect-selected-text', this.$container).html(selectedOption);  
                    }   
                    else   
                    {  
                        $('.multiselect .multiselect-selected-text', this.$container).text(selectedOption);  
                    }  
  
                    $('.multiselect', this.$container).attr('title', selectedOption);  
  
                    labelId = $(ucParentDiv).find("[id*='lblSelectedItems']");  
                    hdnTextId = $(ucParentDiv).find("[id*='hdnText']");  
                    hdnValueId = $(ucParentDiv).find("[id*='hdnValue']");  
  
                    //resetting the label value to ""      
                    $(labelId).html("");  
                    //Setting the display css property value to "none".      
                    $(labelId).css("display", "none");  
  
                    selectedItemsText = options.text();  
                    selectedItemsValue = options.val();  
                }  
            }  
  
            //finally storing the value to the respective hidden fields.      
            $(hdnTextId).val(selectedItemsText);  
            $(hdnValueId).val(selectedItemsValue);  
        }  
  
  
        //Iterating over each DropdownList on which we need to bind our Bootstrap MultiSelect.      
        $("select[id*='ddlAutoCompleteSelect']").each(function()   
        {  
            varddlCntrl = $(this);  
            //retrieving the parent element of the dropdownlist control.      
            vardivUCParent = $(ddlCntrl).parent();  
  
            //retrieving the values of the hidden fields/ property values      
            hdnButtonWidth = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnButtonWidth")).val();  
            hdnNonSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnNonSelectedText")).val();  
            hdnIncludeSelectAllOption = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnIncludeSelectAllOption")).val().toString().toLowerCase());  
            hdnSelectAllText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnSelectAllText")).val();  
            hdnEnableFiltering = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnEnableFiltering")).val().toString().toLowerCase());  
            hdnEnableFilteringIgnoreCase = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnEnableFilteringIgnoreCase")).val().toString().toLowerCase());  
            hdnDisableIfEmpty = convertToBoolean($("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnDisableIfEmpty")).val().toString().toLowerCase());  
            hdnMaxHeight = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnMaxHeight")).val();  
            hdnFilterPlaceholder = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnFilterPlaceholder")).val();  
            hdnAllSelectedText = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnAllSelectedText")).val();  
            hdnSelectionMode = $("#" + ddlCntrl.attr("id").replace("ddlAutoCompleteSelect", "hdnSelectionMode")).val();  
  
            //Retrieving the SelectionMode property value.      
            varinputType = hdnSelectionMode;  
  
            //Applying Bootstrap MultiSelect on DropDownList.      
            $(this).multiselect({  
                buttonWidth: hdnButtonWidth,  
                includeSelectAllOption: hdnIncludeSelectAllOption,  
                enableFiltering: hdnEnableFiltering,  
                enableCaseInsensitiveFiltering: hdnEnableFilteringIgnoreCase,  
                selectAllText: hdnSelectAllText,  
                nonSelectedText: hdnNonSelectedText,  
                disableIfEmpty: hdnDisableIfEmpty,  
                maxHeight: hdnMaxHeight,  
                filterPlaceholder: hdnFilterPlaceholder,  
                allSelectedText: hdnAllSelectedText,  
                buttonText: function(options, select)  
                {  
                    if (options.length === 0)   
                    {  
                        returnthis.nonSelectedText;  
                    }   
                    else  
                    {  
                        var selected = '';  
                        //For fetching the selected option if the SelectionMode for Dropdownlist is Multiple. i,e. Checkbox.      
                        if (inputType === "checkbox")   
                        {  
                            options.each(function()   
                            {  
                                var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();  
                                selected += "<li>" + label + "</li>";  
                            });  
                        }   
                        else   
                        {  
                            //For retrieving the selected option text if the SelectionMode for Dropdownlist is Single. i.e. RadioButton      
                            selected = options.text();  
                        }  
                        return selected;  
                    }  
                }  
            });  
  
            //For keeping the current dropdownlist open after postback      
            if (inputType === "checkbox")  
            {  
                if (postBackElementID == $(this).attr("id"))  
                {  
                    //finding the div with class .btn-group      
                    vardivButtonGroup = $("#" + divUCParent.attr("id")).find(".btn-group");  
                    $(divButtonGroup).addClass("open");  
                }  
            }  
        });  
    });  
}  

Default.aspx

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%><%@RegisterSrc="~/UserControl/AutoCompleteDdl.ascx"TagName="AutoCompleteDdl"TagPrefix="uc1"%>  
<!DOCTYPEhtml>  
<html  
    xmlns="http://www.w3.org/1999/xhtml">  
    <headrunatheadrunat="server">  
        <title>Bootstrap Multiselect</title>  
        <linkrellinkrel="stylesheet"type="text/css"href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"/>  
        <linkrellinkrel="stylesheet"type="text/css"href="Style/bootstrap-multiselect.css"/>  
        <scripttypescripttype="text/javascript"src="Scripts/jquery-1.9.1.min.js">  
        </script>  
    </head>  
    <body>  
        <formidformid="form1"runat="server">  
            <asp:ScriptManagerIDasp:ScriptManagerID="ScriptManager1"runat="server">  
            </asp:ScriptManager>  
            <asp:UpdatePanelIDasp:UpdatePanelID="udpMain"runat="server">  
                <ContentTemplate>  
                    <divclassdivclass="container">  
                        <divclassdivclass="row">  
                            <divclassdivclass="col-md-12">  
                                <h3>Bootstrap MultiSelectDropdownlist</h3>  
                                <table>  
                                    <tbody>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <h4>Single Select Option</h4>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdvaligntdvalign="top">Select Item:   
                                            </td>  
                                            <td>  
                                                <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlSingleSelect"runat="server"IncludeSelectAllOption="false"  
AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"  
MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."  
SelectionMode="Single"PlaceHolder="Select a Keyword"/>  
                                                <p>  
                                                    <asp:ButtonIDasp:ButtonID="btnSingleSelect"runat="server"Text="Get Data"OnClick="btnSingleSelect_Click"/>  
                                                </p>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <asp:LabelIDasp:LabelID="lblSingleSelectData"runat="server"/>  
                                            </td>  
                                        </tr>  
                                    </tbody>  
                                </table>  
                            </div>  
                        </div>  
                        <divclassdivclass="row">  
                            <divclassdivclass="col-md-12">  
                                <table>  
                                    <tbody>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <h4>Multi Select WithAutoPostBack</h4>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdvaligntdvalign="top">Select Item:   
                                            </td>  
                                            <td>  
                                                <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlMultiSelect"runat="server"IncludeSelectAllOption="false"  
AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"  
MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."  
SelectionMode="Multiple"PlaceHolder="Select a Keyword"/>  
                                                <p>  
                                                    <asp:ButtonIDasp:ButtonID="btnMultiSelect"runat="server"Text="Get Data"OnClick="btnMultiSelect_Click"/>  
                                                </p>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <asp:LabelIDasp:LabelID="lblMultiSelectData"runat="server"/>  
                                            </td>  
                                        </tr>  
                                    </tbody>  
                                </table>  
                            </div>  
                        </div>  
                        <divclassdivclass="row">  
                            <divclassdivclass="col-md-12">  
                                <table>  
                                    <tbody>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <h4>Multi Select With AutoPostback And Dependent DDL</h4>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdvaligntdvalign="top">Select Item:   
                                            </td>  
                                            <td>  
                                                <uc1:AutoCompleteDdlIDuc1:AutoCompleteDdlID="ddlPrimaryMultiSelect"runat="server"IncludeSelectAllOption="false"  
AutoPostBack="true"ButtonWidth="320px"SelectAllText="All"NonSelectedText="--Select Option--"  
MaxHeight="400"EnableFiltering="true"FilterPlaceholder="Search For Something..."  
SelectionMode="Single"PlaceHolder="Select a Keyword"/>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <td>Select Another Item:</td>  
                                            <td>  
                                                <asp:DropDownListIDasp:DropDownListID="ddlDependent"runat="server"CssClass="dropdown">  
                                                </asp:DropDownList>  
                                            </td>  
                                        </tr>  
                                        <tr>  
                                            <tdcolspantdcolspan="2">  
                                                <asp:LabelIDasp:LabelID="lblMultiPostbckData"runat="server"/>  
                                            </td>  
                                        </tr>  
                                    </tbody>  
                                </table>  
                            </div>  
                        </div>  
                    </div>  
                </ContentTemplate>  
            </asp:UpdatePanel>  
        </form>  
    </body>  
</html>  

Default.aspx.cs

using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Web;  
usingSystem.Web.UI;  
usingSystem.Web.UI.WebControls;  
  
publicpartialclass_Default: System.Web.UI.Page   
{  
    List < SelectModel > lstData = newList < SelectModel > ();  
    List < SelectModel > lstDependent = newList < SelectModel > ();  
  
    protectedvoidPage_Load(object sender, EventArgs e)   
    {  
        if (!IsPostBack)  
        {  
            LoadData();  
            LoadSingleSelectData();  
            LoadMultiSelectData();  
            LoadPrimaryMultiSelect();  
        }  
        ddlPrimaryMultiSelect.SelectedIndexChanged += ddlPrimaryMultiSelect_SelectedIndexChanged;  
    }  
  
    publicvoidddlPrimaryMultiSelect_SelectedIndexChanged(object sender, EventArgs e) {  
        LoadDependentDDL();  
    }  
  
    privatevoidLoadData()   
    {  
        for (inti = 0; i < 5; i++)   
        {  
            lstData.Add(newSelectModel()  
            {  
                Value = "Item " + i, Text = "Item " + i  
            });  
        }  
    }  
  
    privatevoidLoadSingleSelectData()  
    {  
        ddlSingleSelect.DataValueField = "Value";  
        ddlSingleSelect.DataTextField = "Text";  
        //Setting the data source for the dropdownlist    
        ddlSingleSelect.DataSource = lstData;  
    }  
  
    privatevoidLoadMultiSelectData()   
    {  
        ddlMultiSelect.DataValueField = "Value";  
        ddlMultiSelect.DataTextField = "Text";  
        ddlMultiSelect.DataSource = lstData;  
    }  
  
    privatevoidLoadPrimaryMultiSelect()   
    {  
        ddlPrimaryMultiSelect.DataValueField = "Value";  
        ddlPrimaryMultiSelect.DataTextField = "Text";  
        ddlPrimaryMultiSelect.DataSource = lstData;  
    }  
  
    privatevoidLoadDependentDDL()  
    {  
        stringselectedItem = ddlPrimaryMultiSelect.SelectedItem.Text;  
        stringsubItem = "Sub " + selectedItem;  
        lstDependent.Clear();  
        lstDependent.Add(newSelectModel()   
        {  
            Text = subItem, Value = subItem  
        });  
        ddlDependent.DataValueField = "Value";  
        ddlDependent.DataTextField = "Text";  
        ddlDependent.DataSource = lstDependent;  
        ddlDependent.DataBind();  
    }  
  
    protectedvoidbtnSingleSelect_Click(object sender, EventArgs e) {  
        string value = ddlSingleSelect.Value;  
        string text = ddlSingleSelect.Text;  
  
        lblSingleSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;  
    }  
  
    protectedvoidbtnMultiSelect_Click(object sender, EventArgs e)   
    {  
        string value = ddlMultiSelect.Value;  
        string text = ddlMultiSelect.Text;  
  
        lblMultiSelectData.Text = "<b>Value: </b>" + value + "<br/><b>Text: </b>" + text;  
    }  
  
} 

حالا اپ را اجرا کنید، خروجی زیر را خواهید دید.

DropDownList

موفق باشید !

  • پسورد: www.mspsoft.com
داریوش فرخی

داریوش فرخی هستم از سال 92 شروع به یادگیری برنامه نویسی و از سال 93 در بخش برنامه نویسی و تولید محتوای سایت mspsoft.com مشغول هستم. فعالیتم نیز بیشتر در زمینه های برنامه نویسی با سی شارپ و asp.net بوده است. اوقات فراغتم را هم غالبا با تماشای فیلم یا بازی های کامپیوتری پر میکنم .

نوشته‌های مرتبط

دیدگاه‌ها

*
*

این سایت از اکیسمت برای کاهش هرزنامه استفاده می کند. بیاموزید که چگونه اطلاعات دیدگاه های شما پردازش می‌شوند.

کدیشن ! مارکت پروژه های برنامه نویسی راه اندازی شدیه توکه پا بریم ببینم