当用户单击单选按钮时触发事件

Firing an event when a user clicks a radio button

我需要根据用户在单选按钮中的选择使某些控件可见或不可见,但我需要在用户单击 后立即使这些控件可见或不可见单选按钮之一。

我尝试在 ASP 端添加 OnSelectedIndexChanged,但它似乎没有任何作用。单击其中一个单选按钮后,是否有其他方法可以立即触发代码?

目前我有:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server" OnSelectedIndexChanged="rblMeasurementSystem_SelectedIndexChanged">
  <asp:ListItem Text="Leads" Value="1" />
  <asp:ListItem Text="Audit Thresholds" Value="2" />
  <asp:ListItem Text="Root Cause" Value="3" />
  <asp:ListItem Text="Pend Reasons" Value="4" />
  <asp:ListItem Text="AA Review" Value="5" />
</asp:RadioButtonList>

在代码隐藏中我有:

protected void rblMeasurementSystem_SelectedIndexChanged(object sender, EventArgs e)
{
  string value = rblMeasurementSystem.SelectedItem.Value.ToString();
  if (value == "1")
    {
        lblLabel1.Visible = true;
        txtText1.Visible = true;
        lblLabel2.Visible = false;
        txtText2.Visible = false;
        lblLabel3.Visible = false;
        txtText3.Visible = false;
        lblLabel4.Visible = false;
        txtText4.Visible = false;
        lblLabel5.Visible = false;
        txtText5.Visible = false;
    }

  if (value == "2")
    {
        lblLabel1.Visible = false;
        txtText1.Visible = false;
        lblLabel2.Visible = true;
        txtText2.Visible = true;
        lblLabel3.Visible = false;
        txtText3.Visible = false;
        lblLabel4.Visible = false;
        txtText4.Visible = false;
        lblLabel5.Visible = false;
        txtText5.Visible = false;
    }

  if (value == "3")
    {
        lblLabel1.Visible = false;
        txtText1.Visible = false;
        lblLabel2.Visible = false;
        txtText2.Visible = false;
        lblLabel3.Visible = true;
        txtText3.Visible = true;
        lblLabel4.Visible = false;
        txtText4.Visible = false;
        lblLabel5.Visible = false;
        txtText5.Visible = false;
    }

    etc...

}

您的代码的问题在于,代码永远不会回传到服务器(原因是像 ASP RadioButtonCheckBox 控件公开缓存的事件意味着它们将仅在实际回发发生时触发,例如通过按钮)。只需将 AutoPostBack 属性 设置为 true 即可强制回发:-

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server" AutoPostBack="true" 
     OnSelectedIndexChanged="rblMeasurementSystem_SelectedIndexChanged">

此外,如果您只是根据单选按钮选择显示\隐藏一些控件,您应该在客户端使用 JavascriptjQuery.

执行此操作