ASP.NET Radio button checked changed event not firing for first radio button

丶灬走出姿态 提交于 2020-01-02 08:08:23

问题


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>

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();
    };
}

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.


回答1:


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);
}

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.



来源:https://stackoverflow.com/questions/37738031/asp-net-radio-button-checked-changed-event-not-firing-for-first-radio-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!