我在页面上有一个CheckBoxList
。页面上的所有控件均位于 UpdatePanel
中。
<asp:CheckBoxList ID="AreaCheckBoxList" Width="300px" runat="server" onchange="RemoveItems()" RepeatDirection="Horizontal">
<asp:ListItem Value="" style="display: none"></asp:ListItem>
</asp:CheckBoxList>
使用 JavaScript 单击 anchor 标记时向其添加项目。
<a class="button" onclick="addToCheckBoxListControl()" />
function addToCheckBoxListControl() {
var tableRef = document.getElementById('<%= AreaCheckBoxList.ClientID %>');
var list = document.getElementById('<%= AreaDropDownList.ClientID %>');
var valueValue = list.options[list.selectedIndex].value;
var textvalue = list.options[list.selectedIndex].text;
if (!isValueAlreadyExist(tableRef, valueValue)) {
var rowArray = tableRef.getElementsByTagName('tr');
var rowCount = rowArray.length;
var rowElement = tableRef.insertRow(rowCount);
var columnElement = rowElement.insertCell(0);
var checkBoxRef = document.createElement('input');
var labelRef = document.createElement('label');
checkBoxRef.type = 'checkbox';
checkBoxRef.value = valueValue;
labelRef.innerHTML = textvalue;
columnElement.appendChild(checkBoxRef);
columnElement.appendChild(labelRef);
}
}
我在页面上有一个按钮,CheckBoxList
控制在单击按钮后丢失所有项目(使用 javascript 添加项目)。
AreaCheckBoxList.Items.Count -----> =1
最佳答案
您似乎正在将数据绑定(bind)到 CheckBoxList
从后面的代码中,您正在检查 IsPostBack
在数据绑定(bind)之前。因此您的数据仅可用于直接页面加载,不可用于回发。
编辑
<小时/>您的问题似乎是 JavaScript 代码在回发后未执行。您可以在 updatepanel 完成请求时注册 JavaScript 函数。尝试使用此代码在 updatepanel 完成请求后调用您的 JavaScript 函数。
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(addToCheckBoxListControl)
http://msdn.microsoft.com/en-us/library/bb397523(v=vs.100).aspx
The pageLoaded event is raised after all content on the page is refreshed, whether it was refreshed because of a synchronous (full-page) postback or an asynchronous postback. You can use this event to provide a custom transition effect for updated content.
更新2
<小时/>您只问了问题的一部分。看来真正的问题是,您正在将项目添加到 CheckBoxList
使用 JavaScript 并希望在代码隐藏中访问它。这不可能。如果您修改了 CheckBoxList
在 JavaScript 中,它不会在服务器端持久存在,并且会在发生 PostBack 后消失。
所以我对这种情况的建议是,替换你的 <a>
带有 asp.net 链接按钮的标记,当您单击时它将执行回发。在该单击事件上,您可以在服务器端添加元素。因此它可以为您提供服务器端和客户端。
关于javascript - CheckBoxList 控件在回发后丢失所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497811/