简体   繁体   English

Asp .net 下拉列表 SelectedItem 在下拉列表中清除后不会更改

[英]Asp .net dropdownlist SelectedItem doesn't change after clear in dropdownlist

I'm using the asp: DropDownList component with jquery Select2.我正在使用带有 jquery Select2 的 asp: DropDownList 组件。 It works but I expect to change the DropDownList SelectedItem property when I clear the item in DropDownList.它可以工作,但我希望在清除 DropDownList 中的项目时更改 DropDownList SelectedItem 属性。 As I understand, when I clear the item it is changing but again back to the previous state because of PostBack.据我了解,当我清除该项目时,它正在更改,但由于 PostBack 再次回到以前的 state。

In Aspx file looks like this;在 Aspx 文件中看起来像这样;

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

The scripts for the Select2(); 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(); Page_Init();

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

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.在 DropDownList.DataBind() 调用之后,我在 Page_Init() function 中添加了 static 数据。 The static data; static数据;

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.在初始化 Select2 组件时,我们必须确定占位符的 id,该占位符必须与上述 LisItem.Value 属性值相同。 Such as this;比如这样;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM