不要在单击 ASP 按钮时重新加载下拉列表

本文关键字:新加载 加载 下拉列表 单击 ASP 按钮 | 更新日期: 2023-09-27 18:36:47

当我按下按钮时,我正在尝试保存下拉列表的值,但是当我按下按钮时,它似乎刷新页面并永远获得下拉列表列表的索引 0。下面是来自方法 btnAccept_Click 来自 .cs 的代码:

if (comboOpciones.SelectedIndex == 1)
{
    if (serv.modifyMovie(comboModifica.selectedIndex + 1, textboxTitulo.Text, Convert.ToInt32(textboxAño.Text), textBoxGenero.Text, textboxNacionalidad.Text, 0) == 1)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert(' Succesful Modify ');</script>");
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert(' Unsuccesful modify');</script>");
    }
}

值 'comboModifica.selectedIndex' 返回索引 0 的所有时间

这是我的网络表单ASP的代码:

<table class="centrada">
  <tr>
    <td>
    </td>
    <td>
      <p>¿Qué desea hacer?</p>
      <asp:DropDownList ID="comboOpciones" runat="server" AutoPostBack="True" OnSelectedIndexChanged="comboOpciones_SelectedIndexChanged">
        <asp:ListItem>Añadir</asp:ListItem>
        <asp:ListItem>Modificar</asp:ListItem>
      </asp:DropDownList>
    </td>
    <td>
    </td>
    <td>
      <div runat="server" id="divModificar">
        <p>Introduce ID de película a modificar:</p>
        <asp:DropDownList ID="comboModifica" runat="server"></asp:DropDownList>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <asp:Label ID="Label1" runat="server" Text="Nuevo título:"></asp:Label>
    </td>
    <td>
      <asp:TextBox ID="textboxTitulo" runat="server" MaxLength="30"></asp:TextBox>
    </td>
    <td>
      <asp:Label ID="Label2" runat="server" Text="Año:"></asp:Label>
    </td>
    <td>
      <asp:TextBox ID="textboxAño" runat="server" MaxLength="4"></asp:TextBox>
    </td>
  </tr>
  <tr>
    <td>
      <asp:Label ID="Label3" runat="server" Text="Género:"></asp:Label>
    </td>
    <td>
      <asp:TextBox ID="textBoxGenero" runat="server" MaxLength="15"></asp:TextBox>
    </td>
    <td>
      <asp:Label ID="Label4" runat="server" Text="Nacionalidad:"></asp:Label>
    </td>
    <td>
      <asp:TextBox ID="textboxNacionalidad" runat="server" MaxLength="25"></asp:TextBox>
    </td>
  </tr>
  <tr>
    <td>
      <asp:Label ID="Label5" runat="server" Text="Director:"></asp:Label>
    </td>
    <td>
      <asp:DropDownList ID="comboDirectores" runat="server"></asp:DropDownList>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
  <tr>
    <td colspan="4">
      <asp:Button ID="btnAccept" runat="server" Text="Enviar" AutoPostBack="false" OnClick="btnAccept_Click"/>
    </td>
  </tr>
</table>

如何获取下拉列表的值?

不要在单击 ASP 按钮时重新加载下拉列表

您的问题是,组合框在每个回发中都会初始化。因此,您需要确定它是否是回发。仅当组合框不是回发时才初始化组合框。Let BindMyCbo() 是将所有值绑定到所需组合框的方法,这里是comboModifica 。然后,仅当页面加载不是回发时,才需要调用该方法。因此,方法调用(在page_load事件中)将如下所示:

 if (!IsPostBack)
    {
        BindMyCbo();
        //Rest of code
    }

因此,组合框在页面加载中初始化,并在回发后保持不变