[英]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>
<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>
這樣可以節省以下步驟的時間。
- 從客戶前往
- IIS Web服務器
- ISAPI擴展
- ISAPI Extension加載/執行/將aspx轉換為HTML
- 發送回IIS Web服務器。
- 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.