2016-10-10 26 views
0

我有一個複選框列表,某些用戶的某些項目被禁用。item.Selected在checkboxlist被禁用時爲false。

enter image description here

當我點擊 '保存',下面的代碼被執行。

foreach (ListItem item in myCheckBoxList.Items) 
{ 
    if (!item.Selected) 
      { 
       continue; 
      } 
    selectedValues.Add(item.Value); 
    } 

但是,即使已選中item.Selected,對於禁用的項目,其評估結果爲false。

有沒有辦法解決這個問題?

+0

我想這是因爲禁用複選框並沒有真正發送到服務器POST。看到[這個答案](http://stackoverflow.com/questions/4727974/how-to-post-submit-an-input-checkbox-that-is-disabled) –

回答

1

如果CheckBoxList的ListItems與aspnet一起添加,無論是在代碼後面還是在.aspx頁面中,ViewState都將確保它將看到已禁用的複選框,即使它們沒有發送到服務器。

protected void Button1_Click(object sender, EventArgs e) 
    { 
     List<string> selectedValues = new List<string>(); 
     Label1.Text = ""; 
     foreach (ListItem item in myCheckBoxList.Items) 
     { 
      if (item.Selected) 
      { 
       selectedValues.Add(item.Value); 
       Label1.Text += item.Value + "<br>"; 
      } 
     } 
    } 

而且使完成這個例子:

<asp:Label ID="Label1" runat="server" Text=""></asp:Label> 
    <br /><br /> 
    <asp:CheckBoxList ID="myCheckBoxList" runat="server"> 
     <asp:ListItem Text="Blueberry" Value="Blueberry"></asp:ListItem> 
     <asp:ListItem Text="Raspberry" Value="Raspberry"></asp:ListItem> 
     <asp:ListItem Text="Blackberry" Value="Blackberry"></asp:ListItem> 
     <asp:ListItem Text="Strawberry" Value="Strawberry" Enabled="false" Selected="True"></asp:ListItem> 
     <asp:ListItem Text="Gooseberry" Value="Gooseberry" Enabled="false" Selected="True"></asp:ListItem> 
    </asp:CheckBoxList> 
    <br /><br /> 
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 
+0

這已經正是我正在做的,它不起作用。 –

+0

發佈前自己測試過。我可以向你保證它確實如此。也許你的問題在別的地方,比如在ListItems的招標中。 – VDWWD

3

禁用的輸入不會發布到服務器,因此它將被設置爲默認值,即false。您可以使用HiddenField並將其與每個複選框相關聯,並根據它的選擇設置它的值。

+0

這是不正確的。你甚至測試過它嗎?它們不會發布到服務器,但這並不意味着aspnet不會將它們重新調整爲已檢查。 – VDWWD

+0

什麼?他們沒有發佈到服務器,但這並不意味着aspnet不會重新調整他們爲檢查?如果某些事情甚至沒有發佈,那麼它將如何被識別爲檢查? – Imad

+0

@Imad謝謝。我沒有意識到他們沒有發佈到服務器。我現在有一個解決方案。謝謝。 –

相關問題