【问题标题】:ASP.NET Radio button checked changed event not firing for first radio buttonASP.NET 单选按钮检查更改事件未触发第一个单选按钮
【发布时间】:2016-10-10 19:39:26
【问题描述】:

我面临一个问题,即第一个单选按钮的选中更改事件未触发。我启用了ViewState,但问题仍然存在。请看以下代码:

<span class="pull-right text-right">
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewAll" CausesValidation="false" GroupName="Filter" Text="View All" AutoPostBack="true" EnableViewState="true" Checked="true" />
    </label>
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewCurrent" CausesValidation="false" GroupName="Filter" Text="View Current" AutoPostBack="true" />
    </label>
    <label class="inline radio">
        <asp:RadioButton runat="server" ID="rdoViewFuture" CausesValidation="false" GroupName="Filter" Text="View Future" AutoPostBack="true" />
    </label>
</span>

我在Page_Init 上设置选中的更改事件,如下所示:

public void Page_Init(object sender, EventArgs e)
{
    this.rdoViewAll.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
    this.rdoViewFuture.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
    this.rdoViewCurrent.CheckedChanged += (s, a) =>
    {
        RebindTerms();
    };
}

我注意到的一件事是,当我删除第一个单选按钮上的 Checked="true" 属性时,CheckedChanged 事件会成功触发。但是,我需要在页面加载时默认选中第一个单选按钮。

【问题讨论】:

  • 我相信您已经知道,如果不选中另一个单选按钮,就无法取消选中组中的单选按钮。这样,CheckedChanged 事件只会触发剩余的未选中 RadioButton 而不是已选中的 RadioButton,因此在您的情况下,rdoViewAll 是您的默认事件,该事件只会触发 rdoViewFuture 和 rdoViewCurrent。
  • 我建议你改用 Click 事件。
  • @Dr.Stitch - RadioButton 没有可以在代码隐藏中处理的 Click 事件。
  • 是的,我建议的是一个 javascript 点击事件。

标签: c# asp.net radio-button


【解决方案1】:

您最初可以为所有 RadioButtons 留下Checked="false",并使用客户端代码设置选定的按钮:

private RadioButton selectedRadioButton;

protected void Page_Load(object sender, EventArgs e)
{
    selectedRadioButton = rdoViewAll;

    if (rdoViewCurrent.Checked)
    {
        selectedRadioButton = rdoViewCurrent;
    }

    if (rdoViewFuture.Checked)
    {
        selectedRadioButton = rdoViewFuture;
    }

    rdoViewAll.Checked = false;
    rdoViewCurrent.Checked = false;
    rdoViewFuture.Checked = false;

    ClientScript.RegisterStartupScript(GetType(), "InitRadio", string.Format("document.getElementById('{0}').checked = true;", selectedRadioButton.ClientID), true);
}

单击任何 RadioButton 将始终触发 CheckedChanged 事件。实际选中的 RadioButton 存储在selectedRadioButton 中,如果您在服务器代码的其他部分需要它。

【讨论】:

  • 您好,我现在遇到了上面代码的问题。在几次回发后第二次选择第一个单选按钮时,它不起作用。知道可能是什么问题吗?
  • 我修改了答案以在您单击 RadioButton 时触发事件,即使它已被选中。
猜你喜欢
  • 2011-12-24
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 2011-12-13
相关资源
最近更新 更多