且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加用户控件消失,当我点击它

更新时间:2023-11-30 15:34:52

您是正确的,页面被重建,所以你必须重新创建与每一个部分或完全回发的控件树。

You are correct, the page is rebuilt, thus you must recreate the control tree with every partial or complete postback.

要做到这一点,就必须让你的页面状态或包含足够的信息来重新创建每次往返控件树。每一个方法都有其优点/缺点。

To accomplish this, you must make your page stateful or include enough information to recreate the control tree with every roundtrip. Every approach has its advantages/disadvantages.

状态

最有可能是有状态的页面将使用会话;必须小心,不要过多的数据转储到会议和清理正确(我通常使用一个经理来包装会话和管理用户可​​以有多少活动对象必须在一次)。好处是会话(甚至退出过程)是非常快速和安全的。

Most likely a stateful page will use Session; care must be taken not to dump too much data into Session and to cleanup properly (I usually use a manager to wrap Session and manage how many active objects a user can have at once). The upside is that Session (even out of process) is very fast and secure.

往返

此方法使用ViewState中,隐藏字段或信息的URL。如果信息包含的页面,它应该被测量的字节,即它应该是非常小的。它也不能幸免于被篡改。

This approach uses ViewState, hidden fields, or information in the URL. If information is included with the page, it should be measured in bytes, i.e. it should be extremely small. It is also not immune to tampering.

好处是,你真的没有做太多,使这项工作,有必要清理处置没有过程。

The upside is that you really don't have to do much to make this work, and there is no disposition process needed to cleanup.

数据库

另外,你可以坚持你的变化与每次点击一个数据库,并从数据库中重建树,但除非点击重新presents非常显著的事件我不是通常不是这种方法的风扇和数据的完整性和验证。

Alternatively, you could persist your changes to a database with every click and rebuild the tree from the database, but I'm not usually not a fan of this approach unless the click represents a very significant event and the data is complete and validated.

很简单的例子

下面是显示使用Session保持控制树的例子。这应该工作,但它没有考虑很多事情,如用户在同一任务中打开同一页的另一个副本。管理控制树可以得到相当复杂的。

Here is an example showing the use of Session to maintain a control tree. This should work but it doesn't account for many things, such as the user opening another copy of the same page in the same session. Managing control trees can get quite complex.

private List<string> _listOfStrings
{
   get
   {
     return (List<string>)Session["_listOfStrings"];
   }
   set
   {
     Session["values"] = value;   
   }
}

protected override OnInit( EventArgs e )
{
    if( !Page.IsPostback )
    {
        _listOfStrings = new List<string>();
    }

    BuildControlTree();
}

private void BuildControlTree()
{
   foreach( string s in _listOfStrings )
   {
     // add a control to the control tree
   }
}

protected void btnAddItem_Click( object sender, EventArgs e )
{
    _listOfStrings.Add( "some new item" );

    // insert the control into the tree
}