Asp .net dropdownlist SelectedItem doesn’t change after clear in dropdownlist

I’m using the asp: DropDownList component with jquery Select2. It works but I expect to change the DropDownList SelectedItem property when I clear the item in DropDownList. As I understand, when I clear the item it is changing but again back to the previous state because of PostBack.

In Aspx file looks like this;

 <asp:DropDownList
       ID="countriesDdl"
       AutoPostBack="true"
       runat="server"
       class="js-example-placeholder-single" Width="200">
 </asp:DropDownList>

The scripts for the Select2();

 <script type="text/javascript">
    $(document).ready(function () {
        $("#<%=countriesDdl.ClientID%>").select2();
        $(".js-example-placeholder-single").select2({
            placeholder: "Select a code",
            allowClear: true,
            selectOnClose: false
        });
    });
</script>

Page_Init();

        countriesDdl.DataSource = countries;
        countriesDdl.DataTextField = "TEST";
        countriesDdl.DataValueField = "TESTID";
        countriesDdl.DataBind();

Answer

I got a solution. It may be a workaround solution but works for me; I added static data In the Page_Init() function after DropDownList.DataBind() call. The static data;

countriesDdl.Items.Insert(0, new ListItem { Text = "Select a code", Value = "0" });

But it wasn’t enough. When initializing the Select2 component we must determine the id for a placeholder that of the must same with at the above LisItem.Value property value. Such as this;

 <script type="text/javascript">
    $(document).ready(function () {
        $("#<%=countriesDdl.ClientID%>").select2({
                placeholder: {
                    id: 0,
                    text: "Select a code"
                },
                allowClear: true
            });
        });
 </script>

Leave a Reply

Your email address will not be published. Required fields are marked *