2012-06-16 21 views
2

我想在用戶單擊ASP.NET中的提交按鈕時禁用選中複選框。我可以使用JavaScript按鈕的onclick事件禁用複選框。複選框位於Repeater中。當通過單擊提交按鈕提交表單時,沒有任何複選框顯示爲在代碼隱藏按鈕點擊代碼中選中。如何在點擊提交按鈕時禁用選中的複選框,並在提交頁面時仍然可以看到複選框已選中?有沒有解決辦法?我的首選是使用JavaScript來做到這一點,但我也願意使用jQuery。當單擊提交按鈕時禁用中繼器中的複選框

function disableCheckboxes() { 
    for (var count = 0; i < document.forms[0].elements.length; i++) 
    { 
     if (document.forms[0].elements[count].type == 'checkbox') 
     { 
      document.forms[0].elements[count].disabled = true; 
     } 
    } 
} 
<form id="form1" runat="server"> 
<div> 
    <table> 

     <asp:Repeater ID="rptCustomer" runat="server" OnItemDataBound="DisplayCustomerRepeater_ItemDataBound"> 
      <ItemTemplate> 
       <tr> 
        <td> 
         <asp:CheckBox ID="checkSubscription" runat="server" /> 
        </td> 
        <td> 
         <%# ((Customer)Container.DataItem).FirstName + " " + ((Customer)Container.DataItem).LastName%> 
        </td> 
       </tr> 
       <tr> 
        <td> 
         <hr /> 
        </td> 
       </tr> 
      </ItemTemplate> 
     </asp:Repeater> 
    </table> 
</div> 
<div> 
    <asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" 
     Text="Submit" runat="server" /></div> 
</form> 

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!this.IsPostBack) 
    { 
     rptCustomer.DataSource = customers; 
     rptCustomer.DataBind(); 
    } 

    btnSubmit.Attributes.Add("onclick", String.Concat("this.disabled=true;disableCheckboxes();", ClientScript.GetPostBackEventReference(btnSubmit, ""))); 
} 
protected void DisplayCustomerRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) 
{ 
    ListItemType lt = e.Item.ItemType; 
    if (lt == ListItemType.Item || lt == ListItemType.AlternatingItem) 
    { 
     Customer customer = e.Item.DataItem as Customer; 
     if (customer != null) 
     { 
      CheckBox chkCustomer = e.Item.FindControl("checkSubscription") as CheckBox; 
      if (chkCustomer != null) 
      { 
       if (customer.IsEligible) 
       { 
        chkCustomer.Checked = true; 
       } 
      } 
     } 
    } 
} 
protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    bool isChecked = false; 

    foreach (RepeaterItem item in rptCustomer.Items) 
    { 
     CheckBox selectedCheckBox = (CheckBox)item.FindControl("checkSubscription"); 
     if (selectedCheckBox.Checked) 
     { 
      isChecked = true; 
     } 
    } 
} 

回答

2

表單提交時,瀏覽器根本不發送禁用表單元素。

順便說一句,這正是未經檢查的複選框發生的情況。當提交表單時,禁用的選中複選框將被完全處理爲未選中狀態。

因此,如果您在提交表單前禁用所有複選框,則相應的服務器端複選框控件將在回發後全部取消選中。

作爲一種解決方法,您需要將每個文本框的狀態複製到某個其他控件中,然後將其重置爲未選中狀態。然後你可以使用其他字段來檢查你的代碼中的狀態。

+0

更好的解決方法是提交後有250毫秒的簡單延遲(用戶在250毫秒內很少發現任何東西),然後執行OP的操作。這樣,他們不會被禁用,直到發送表單請求之後。 – jcolebrand

+0

謝謝。作爲解決問題的一種方法,我使用了下面的代碼來禁止用戶選中或取消選中提交。 for(var i = 0; i sdobbi

相關問題