Search code examples
c#jqueryasp.netdrop-down-menujquery-select2

jQuery select2 work with dropdownlist asp.net server control


I am trying to use it with asp.net server run dropdownlist. When asp.net control is rendered on the page it has different id something such as: "ctl00_ContentPlaceHolder1_ddlAgentName" although the dropdown list is declared in the code this way:

<asp:DropDownList Selected="True" ID="ddlAgentName" runat="server" CssClass="dropdown nostyle sel1" Width="100%" />

I am trying two scenarios:

  $(document).ready(function () {
             $("#<%=ddlAgentName.ClientID %>").select2({
                minimumInputLength: 4
            });
            $("#ctl00_ContentPlaceHolder1_ddlAgentName").select2({
                minimumInputLength: 4
            });
        });

But none of them wants to work. The rendered HTML output is:

 <select name="ctl00$ContentPlaceHolder1$ddlAgentName" id="ctl00_ContentPlaceHolder1_ddlAgentName" class="dropdown nostyle sel1" Selected="True" style="width:100%;"></select>

I tried normal (non-server) select box and the jQuery script works fine there.


Solution

  • Checkout the ClientIDMode property. That way you can ensure the name of the DDL is the same.

    Alternatively, you can give it a unique class name and get to it that way, but that's a little hacky.