2016-06-10 61 views
3

我面臨的問題是第一個單選按鈕的選中更改的事件未觸發。我啓用ViewState但仍然存在問題。請看下面的代碼:ASP.NET單選按鈕檢查更改的事件不會觸發第一個單選按鈕

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

有一件事我注意到的是,當我刪除第一個單選按鈕CheckedChangedChecked="true"財產事件成功啓動。但是,我需要在頁面加載時默認檢查第一個單選按鈕。

+1

我相信你已經知道你不能不選中另一個組中的RadioButton。因此,CheckedChanged事件只會觸發剩下的取消選中RadioButton,而不是已經檢查過的RadioButton,所以在你的情況下,rdoViewAll是你的默認值,事件只會觸發rdoViewFuture和rdoViewCurrent。 –

+1

我建議你改用Click事件。 –

+0

@ Dr.Stitch - RadioButton沒有可以在代碼隱藏中處理的Click事件。 – ConnorsFan

回答

2

你可以離開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事件。如果您在服務器代碼的其他部分需要它,則實際選定的RadioButton將存儲在selectedRadioButton中。

+0

感謝客戶端腳本在這裏做的伎倆! –

+0

嗨,再次,我現在有一個問題,上面的代碼。在幾次回發之後第二次選擇第一個單選按鈕時它不起作用。任何想法可能是什麼問題? –

+0

我修改了我的答案,在任何時候點擊RadioButton時觸發事件,即使它已被選中。 – ConnorsFan