ASP.NET单选按钮检查的已更改事件未触发第一个单选按钮 [英] ASP.NET Radio button checked changed event not firing for first radio button

查看:40
本文介绍了ASP.NET单选按钮检查的已更改事件未触发第一个单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am facing an issue where the checked changed event of the first radio button is not firing. I enabled ViewState but still the issue persists. Please see below code:

<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 上设置选中的更改事件,如下所示:

And I am setting the checked changed event on Page_Init as below:

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 事件.但是,我需要在页面加载时默认选中第一个单选按钮.

One thing I noticed is when I remove the Checked="true" property on the first radio button the CheckedChanged event fires successfully. However, I need the first radio button to be checked by default on page load.

推荐答案

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

You can leave Checked="false" for all the RadioButtons initially, and set the selected button with client code:

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 中.

Clicking on any RadioButton will always trigger the CheckedChanged event. The RadioButton that is actually selected is stored in selectedRadioButton, if you need it in other parts of the server code.

这篇关于ASP.NET单选按钮检查的已更改事件未触发第一个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆