解决:ListBox 控件在客户端用脚本添加删除项时,后台得不到修改后的数据

来源:互联网 发布:温州网络学堂播放屏蔽 编辑:程序博客网 时间:2024/05/16 07:21

 最近做项目时遇到如题的问题:
         页面上有2个ListBox控件 ListBox控件中间是2个左移,右移按钮,就是实现把2个 listbox 控件中的项左右移动,
         为减少与服务器交互的次数,采用 javascript 脚本来控制移动,  但是这样控制以后,提交到服务器端却怎么也得不到移动数据后的实际值, 2个listbox的值和开始加载时的一样,根本改变, 不知道是什么原因, 网上有说各种原因的,我也不知道对不对,也许是自己水平有限吧, 我自己琢磨了一下,可以利用隐藏域来保存修改,然后在服务器端得到隐藏域里的value,以下是我写的客户端的代码

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
<script type="text/javascript" language="javascript">
        
function SelectOne()
        
{
            
var listBox1=window.document.getElementById("listBox1");
            
var lstindex=listBox1.selectedIndex;
            
if(lstindex<0)
                
return;
            
var v = listBox1.options[lstindex].value;
            
var t = listBox1.options[lstindex].text;
            
var listBox2=window.document.getElementById("listBox2");
            listBox2.options[listBox2.options.length] 
= new Option(t,v,true,true);    
            
var hid = document.getElementById("hid");
            hid.value 
+= t + "-" + v + "|";
            listBox1.remove(lstindex);
        }

    
</script>
</head>
<body>
    
<form id="Form1" runat="server" action="">
    
<div>
        
<asp:ListBox ID="listBox1" runat="server">
        
</asp:ListBox>
        
<input type="button" onclick="SelectOne();" value=">>" />
        
<asp:ListBox ID="listBox2" runat="server">
        
        
</asp:ListBox>
    
</div>
    
<asp:Button ID="save" runat="server" OnClick="save_Click" />
    
<input type="hidden" runat="server" id="hid" />
    
</form>
</body>
</html>


我将选中的值 组合成:  key1 - value1 | key2 - value2 | key3 - value3   的形式保存在hid隐藏控件的 value 上,
然后在服务器端可以 取出 hid 控件的 value 值 ,再按 "|" 进行 split  后得到 键/值 对 的数组 ,
然后再按 "-" 符号 split  ,取出 key 和 value  保存在一个 hashtable 中,
注意: 保存进 hashtable 的时候 判断 如果 key 已经存在 则从 hashtable 中删除此 键/值 对,如不存在则添加
进 hashtable 中, 这样可以清除掉 hid 控件的value值中的重复项( 以上代码是无论添加项 还是移除项 总是在 hid
控件的 value 值上追加 键/值 对)

原创粉丝点击