簡體   English   中英

遍歷asp:CheckBox控件

[英]Looping through asp:CheckBox controls

我的頁面上有11個控件,都是復選框。 它包含在母版頁中。

我可以這樣實現我想要的:

generalInformation.InputAttributes.Add( "class", "SetupChecklist" );
generalInformation2.InputAttributes.Add( "class", "SetupChecklist" );
generalInformation3.InputAttributes.Add( "class", "SetupChecklist" );

等等..

我現在正試圖遍歷這些內容,並做同樣的事情來節省一些代碼,但是要使其正常工作,我遇到了很多麻煩,但是我根本無法使它工作。

誰能給我一個很好的方法來遍歷這11個復選框控件並添加CSS類SetupChecklist?

我嘗試了這個,由於某種原因它沒有添加類。

protected void InitializeCheckboxes ()
    {
        //generalInformation.InputAttributes.Add( "class", "SetupChecklist" );
        var allCheckBoxes = Page.Controls.OfType<CheckBox>();
        foreach ( var c in allCheckBoxes )
        {
            c.InputAttributes.Add( "class", "SetupChecklist" );
        } 
    }

我去調用InitializeCheckboxes(); 在Page_Load方法中。 當我只使用generalInformation.InputAttribues.Add等時,它確實起作用。但是,當我遍歷它們時卻不能。 有什么建議么?

最好將它們放置在Panel (渲染為div)或其他容器控件中。 然后,您可以使用LINQ的OfType獲取引用:

// assuming all checkboxes are in a panel named "SetupContainer"
var allCheckBoxes = SetupContainer.Controls.OfType<CheckBox>();
foreach(var chb in allCheckBoxes)
    chb.InputAttributes.Add( "class", "SetupChecklist" );

當然,您也可以使用它來查找整個頁面上的所有CheckBox,但這可能會出錯。

未經測試,但可能會幫助您。

foreach(Control oControl in Page.Controls)
{
  if(oControl is CheckBox && ((CheckBox)oControl).ID.StartsWith("generalInformation") )
   ((CheckBox)oControl).InputAttributes.Add( "class", "SetupChecklist" );
}

由於runat = "server"您的復選框將呈現如下所示。

<span class="SetupChecklist" class="SetupChecklist" name="generalInformation">
     <input id="generalInformation" type="checkbox" name="generalInformation" />
</span>

JQuery的

<script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $(this).find("input[type='checkbox']").addClass('GuestClass');
    });
</script>

這樣可以節省以下步驟的時間。

  1. 從客戶前往
  2. IIS Web服務器
  3. ISAPI擴展
  4. ISAPI Extension加載/執行/將aspx轉換為HTML
  5. 發送回IIS Web服務器。
  6. IIS響應客戶端
public void GetUserControls(ControlCollection controls)
{
    foreach (Control ctl in controls)
    {
        if (ctl is CheckBoxOrWhateverControlTypeYouWant)
        {
             /// Add attribute
        }

        if (ctl.Controls.Count > 0)
            GetUserControls(ctl.Controls);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM