使用JavaScript设置的值不会在Postback上保留

时间:2010-11-03 16:47:28

标签: javascript asp.net postback

我的asp.net页面中有两个列表控件,并使用javascript填充第二个列表控件。问题是脚本执行,我可以看到值从第一个列表框(ConfiguredOrgListBox)移动到第二个列表框(SelectedOrgListBox)但是当我尝试使用提交按钮保存时,我发现我的第二个列表为空,第一个列表框就像之前一样。下面是脚本和标记。

    //call this method to register the script    
    private void CreateMoveOrganizationScript(StringBuilder sb) {
        sb.Append( @"<script language=javascript type=text/javascript>;
                    function moveOrganisation() {");            
        sb.Append( @"var source = document.getElementById('"+ ConfiguredOrgListBox.ClientID  +@"');
                    var target = document.getElementById('"+SelectedOrgListBox.ClientID+ @"');
                    if ((source != null) && (target != null)) {
                    var newOption = new Option();
                    newOption.text = source.options[source.options.selectedIndex].text;
                    newOption.value = source.options[source.options.selectedIndex].value;

                    target.options[target.length] = newOption;
                    source.remove(source.options.selectedIndex)  ;
                    }            
                } </script>");            
    }

标记

      <asp:Label ID="ConfiguredOrgLabel" runat="server" Text="Available Organizations"></asp:Label><br />
      <asp:ListBox ID="ConfiguredOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
       <input id="MoveOrgRight" type="button" value=">>" onclick="moveOrganisation()" />
      <asp:Label ID="SelectedOrgLabel" runat="server" Text="Selected VNA Organizations"></asp:Label><br />
      <asp:ListBox ID="SelectedOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>

请让我知道我做错了什么

此致 哎呀

2 个答案:

答案 0 :(得分:3)

您需要在回发期间处理这些更改。当回发发生时,ASP.NET引擎从视图状态加载控件的数据,并且它不知道客户端使用javascript修改了值,因此您应该从Request手动提取这些值。

答案 1 :(得分:3)

根据this,这是因为列表框没有回发告诉后端它已被更改。他们使用一个隐藏字段,其中包含有关使用JavaScript进行的更改的信息,然后在回发时更新后端。