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

 最近做项目时遇到如题的问题:
         页面上有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 值上追加 键/值 对)

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bobyzong

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值