ASP.NET单选按钮选中事件对于第一个单选按钮不起作用

3
我遇到了一个问题,第一个单选按钮的checked changed事件没有触发。我启用了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事件会成功触发。然而,我需要在页面加载时默认选中第一个单选按钮。


1
我相信你已经知道在一组RadioButton中,如果不选中另一个RadioButton,则无法取消选中一个RadioButton。因此,CheckedChanged事件只会触发剩余未选中的RadioButton,而不是已经选中的RadioButton。在你的情况下,rdoViewAll是默认选项,事件只会触发rdoViewFuture和rdoViewCurrent。 - Dr. Stitch
1
我建议您使用 Click 事件。 - Dr. Stitch
@Dr.Stitch - RadioButton在代码后台中没有可处理的Click事件。 - ConnorsFan
是的,我建议使用JavaScript点击事件。 - Dr. Stitch
1个回答

3

最开始,您可以为所有的单选按钮将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);
}

点击任何单选按钮都会触发CheckedChanged事件。实际被选中的单选按钮存储在selectedRadioButton中,如果您需要在服务器代码的其他部分使用它。


大家好,我现在遇到了一个问题,就是当第一个单选按钮在几次回发后再次被选择时,上面的代码就无法工作。有什么想法吗? - Bat_Programmer
我修改了我的答案,使得无论单选按钮是否已被选中,都会在单击时触发事件。 - ConnorsFan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接