2011-12-13 49 views
0

在一个asp.net web表单中,我想将值添加回在我的代码中在服务器上创建的.net对象类型中,我拥有以下内容:在asp.net中更新客户端的服务器对象类型

protected void Page_Load (object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       myArrayList.Add("Value 1"); 
       myArrayList.Add("Value 2"); 
       myBox.DataSource = myArrayList; 
      } 
      myBox.DataBind(); 
      myTime.Text = DateTime.Now.ToString(); 
     } 

     protected void btnAddText_Click (object sender, EventArgs e) 
     { 
      myArrayList.Add(mytext.Text.ToString()); 
      myBox.DataSource = myArrayList; 
      myBox.DataBind(); 
     } 

     public ArrayList myArrayList = new ArrayList(); 

我想要做的是将值输入到客户端的文本框中,当单击按钮时,将它们追加到数组中。目前,(如预期)一旦按钮被点击,数组将被重置为空。如果我不使用isPostBack,它只会再次按预期保留最后一个值。我有条件更新Ui中的asp:updatepanels,我意识到asp.net页面生命周期仍然在回发(引起Init,Load,预渲染和卸载)上触发。

我的asp.net是生锈的,但对于像这样的场景是最好的(唯一)方法来使用会话状态并将数组存储在会话中进行操作,或者我错过了什么?

感谢您的任何指导,

回答

0

经过一番更多的研究,我决定去使用会话状态的路线。对于状态管理有很多选项,但会话是我想要做的最直接和最可扩展的选项。

对于这里感兴趣的任何一个工作解决方案显示列表数组被用作会话变量。

在文档我的设置基本区域,按钮,列表框来进行测试:

<table> 
      <tr> 
       <td> 
        <asp:ListBox ID="lstItems" runat="server" Width="200px" Height="120px" /> 
       </td> 
       <td valign="top"> 
        <asp:TextBox ID="myTextBox" Height="32px" runat="server" Width="200px" />&nbsp;&nbsp;<asp:Button 
         Text="Add User" Width="80px" Height="32px" ID="myButton" OnClick="AddNames" runat="server" /> 
       </td> 
      </tr> 
     </table> 

那么后面我设置了以下代码中:我们贡献会话状态的

//简单的例子从UI //类似于SHOPING车示例 会话对象//你可以用任何物体或键入我只是用一个数组,因为它是快速

protected void Page_Load (object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     //Create the session variable and base it upon the array created (this can be any type) 
     Session["myList"] = mainList; 
    } 
} 

protected void AddNames(object sender, EventArgs e) 
{ 
    //Here I set the array to = the Session. key point here is a session object must be cast to the approriate type on assignement 
    mainList = (ArrayList)Session["myList"]; 
    //add to the array 
    mainList.Add(myTextBox.Text.ToString()); 
    //bind to UI 
    lstItems.DataSource = mainList; 
    lstItems.DataBind(); 
    myTextBox.Text = string.Empty; 
} 

ArrayList mainList = new ArrayList();  

使用会话变量时,测试空会话变量(查看变量是否退出)也可能是一个好主意。在某些情况下,如果尝试在创建之前添加到会话中,则失败会导致引发空引用异常。

希望这会有所帮助

0

您还可以使用视图状态,但增加了额外的代码来下载用户得到这会减慢页面交付。另外,我相信我们的对象必须是可序列化的。

+0

谢谢你,你好。是的,你在页面的序列化和“膨胀”中是正确的。如果我必须在他们之间做出选择,我会参加会议状态路线。 – rlcrews