Asp .net 下拉列表 SelectedItem 在下拉列表中清除后不会更改
Asp .net dropdownlist SelectedItem doesn't change after clear in dropdownlist
我将 asp: DropDownList 组件与 jquery Select2 一起使用。它有效,但我希望在清除 DropDownList 中的项目时更改 DropDownList SelectedItem 属性。据我了解,当我清除项目时,它正在发生变化,但由于 PostBack 而再次回到以前的状态。
在 Aspx 文件中看起来像这样;
<asp:DropDownList
ID="countriesDdl"
AutoPostBack="true"
runat="server"
class="js-example-placeholder-single" Width="200">
</asp:DropDownList>
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();
我找到了解决办法。这可能是一种变通解决方案,但对我有用;
我在 DropDownList.DataBind() 调用后的 Page_Init() 函数中添加了静态数据。
静态数据;
countriesDdl.Items.Insert(0, new ListItem { Text = "Select a code", Value = "0" });
但这还不够。在初始化 Select2 组件时,我们必须确定占位符的 ID,该占位符必须与上述 LisItem.Value 属性 值相同。
比如这个;
<script type="text/javascript">
$(document).ready(function () {
$("#<%=countriesDdl.ClientID%>").select2({
placeholder: {
id: 0,
text: "Select a code"
},
allowClear: true
});
});
</script>
我将 asp: DropDownList 组件与 jquery Select2 一起使用。它有效,但我希望在清除 DropDownList 中的项目时更改 DropDownList SelectedItem 属性。据我了解,当我清除项目时,它正在发生变化,但由于 PostBack 而再次回到以前的状态。
在 Aspx 文件中看起来像这样;
<asp:DropDownList
ID="countriesDdl"
AutoPostBack="true"
runat="server"
class="js-example-placeholder-single" Width="200">
</asp:DropDownList>
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();
我找到了解决办法。这可能是一种变通解决方案,但对我有用; 我在 DropDownList.DataBind() 调用后的 Page_Init() 函数中添加了静态数据。 静态数据;
countriesDdl.Items.Insert(0, new ListItem { Text = "Select a code", Value = "0" });
但这还不够。在初始化 Select2 组件时,我们必须确定占位符的 ID,该占位符必须与上述 LisItem.Value 属性 值相同。 比如这个;
<script type="text/javascript">
$(document).ready(function () {
$("#<%=countriesDdl.ClientID%>").select2({
placeholder: {
id: 0,
text: "Select a code"
},
allowClear: true
});
});
</script>