【问题标题】:Firing an event when a user clicks a radio button当用户单击单选按钮时触发事件
【发布时间】:2017-01-31 15:53:03
【问题描述】:

我需要根据用户从单选按钮中的选择使某些控件可见或不可见,但我需要使这些控件可见或不可见只要用户单击其中一个单选按钮.

我尝试在 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...

}

【问题讨论】:

  • 您可以对面板/网格上的控件进行分组,这样您就可以通过一个 .Visible 更改来隐藏它们。
  • 问题是 asp:radio 按钮事件通常是 'runat="server"' 类型:即服务器控件。您正在寻找的是某种与 DOM 和 asp 控件的客户端交互。您需要添加一些 JavaScript 功能/装饰来处理这个“客户端”。
  • @JeroenvanLangen - 好建议!这大大减少了我的代码。

标签: c# asp.net code-behind radiobuttonlist


【解决方案1】:

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

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

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

【讨论】:

    最近更新 更多