防止在ASP.NET中选择默认值时下拉的“选定索引更改”事件

Prevent the Selected Index Changed event of dropdown on selecting the default value in ASP.NET

本文关键字:索引 事件 ASP NET 默认值 选择      更新时间:2023-09-26

我有一个值

的下拉菜单
<asp:DropDownList ID="DropDownList1" runat="server" 
                  onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem>SELECT</asp:ListItem>
    <asp:ListItem>AUS</asp:ListItem>
    <asp:ListItem>BAN</asp:ListItem>
    <asp:ListItem>CAN</asp:ListItem>
    <asp:ListItem>DEN</asp:ListItem>
    <asp:ListItem>ENG</asp:ListItem>
    <asp:ListItem>IND</asp:ListItem>
</asp:DropDownList>

所选索引更改我将项目名称写为:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Write(DropDownList1.SelectedItem);
}

我想当我将选择默认值是选择,事件不应该被调用。只有当我选择除了select以外的任何内容时,才应该调用它。

您可以根据所选择的选项自行PostBack到服务器。

注意: 不要设置DropDownList的AutoPostBack="True"

<asp:DropDownList runat="server" ID="DropDownList1"
    onChange="changeDropDownList();" 
    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Value="" Text="SELECT" />
    <asp:ListItem Value="AUS" Text="AUS" />
    <asp:ListItem Value="BAN" Text="BAN" />
    <asp:ListItem Value="CAN" Text="CAN" />
    <asp:ListItem Value="DEN" Text="DEN" />
    <asp:ListItem Value="ENG" Text="ENG" />
    <asp:ListItem Value="IND" Text="IND" />
</asp:DropDownList>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    function changeDropDownList() {
        // If you want to check by selected text, use this line.
        // var text= $('#<%= DropDownList1.ClientID %> option:selected').text(); 
        var value = $('#<%= DropDownList1.ClientID %> option:selected').val();
        if (value != "") {
            __doPostBack('<%= DropDownList1.ClientID %>', '');
        } else {
            return false;
        }
    }
</script>

最简单的方法之一是使用如下所示的必填字段验证器

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
 ControlToValidate="DropDownList1" ErrorMessage="" InitialValue="SELECT" >
</asp:RequiredFieldValidator>

当你输入InitialValue="SELECT"时它不允许你对SELECT值

进行回发