【发布时间】:2009-12-10 10:43:52
【问题描述】:
我有一个<asp:CheckBoxList> 在我的页面中使用RepeatLayout="Flow" 动态分配值。如果页面是第一次加载(!IsPostBack),渲染的版本类似这样;
<span children="Cat">
<input id="ctl00_Menu_Category_0" type="checkbox" name="ctl00$Menu$Category$0"/>
<label for="ctl00_Menu_Category_0">Cat</label>
</span>
<br/>
<span class="Cat">
<input id="ctl00_Menu_Category_1" type="checkbox" name="ctl00$Menu$Category$1"/>
<label for="ctl00_Menu_Category_1"> - SubCat1</label>
</span>
children 是我用于 jQuery 代码的属性,因此当用户检查 Cat 时,所有 SubCats 也会被检查。
jQuery 代码搜索所有类等于children-attribute 的<span>s,所以我需要维护这个jQuery 工作的结构。
但是,在我重新加载页面或点击链接之后,无论如何,列表突然看起来像这样:
<input id="ctl00_Menu_Category_0" type="checkbox" name="ctl00$Menu$Category$0"/>
<label for="ctl00_Menu_Category_0">Cat</label>
<br/>
<input id="ctl00_Menu_Category_1" type="checkbox" name="ctl00$Menu$Category$1"/>
<label for="ctl00_Menu_Category_1"> - SubCat1</label>
这怎么可能?我只将值分配给列表一次,那么为什么在 PostBack 之后重新渲染它,我该如何防止它这样做呢?
编辑
这是创建列表的代码;
// Get all available categories that are not a child of another category
DataTable categoryParents = functions.SelectSql(Resources.Data.GetCategoryParents);
// Get the child categories
foreach (DataRow parent in categoryParents.Rows)
{
// Add the category
ListItem parentItem = new ListItem(parent["Name"].ToString(), parent["Name"].ToString());
parentItem.Attributes.Add("children", parent["Name"].ToString().Replace(' ', '_'));
Category.Items.Add(parentItem);
// For every parent category, get all its child categories
DataTable categoryChildren = functions.SelectSql(Resources.Data.GetCategoryChildrenByParent.Replace("##PARENTID##", parent["ID"].ToString()));
// Add the child categories after their parents
foreach (DataRow child in categoryChildren.Rows)
{
ListItem item = new ListItem(" - " + child["Name"].ToString(), parent["Name"].ToString() + "\\" + child["Name"].ToString());
item.Attributes.Add("class", parent["Name"].ToString().Replace(' ', '_'));
Category.Items.Add(item);
}
}
Category.DataBind();
jQuery 本身不对 HTML 做任何事情,它只是拥有在检查父项时检查子类别的功能;
$("#Category :checkbox").click(function(){
var checked = $(this).attr("checked");
var children = $(this).parent("span").attr("children");
$("#Category ." + children + " :checkbox").attr("checked", checked);
});
【问题讨论】:
标签: c# asp.net-3.5 postback rendering checkboxlist