且构网

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

问题:在.NET动态控件

更新时间:2023-12-06 10:11:10

ViewState的支持的属性只保留到ViewState中,如果控制正在跟踪的ViewState。这是由设计来保持的ViewState尽可能小:它应该只包含是真正的动态数据。这样做的结果是:

ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that:

Init事件过程中设置的ViewState化子性质是的的后盾,ViewState中(因为网页还没有开始跟踪的ViewState)。因此初始化是个好地方添加控件并设置(一)属性不会回发之间更改(ID,的CssClass ......)以及为动态属性的初始值(然后可以通过code在被修改页面生命周期的其余部分 - 负载,事件处理程序,preRender)

ViewState propeties set during the Init event are not backed to ViewState (because the Page has not yet started tracking ViewState). Thus Init is a good place to add controls and set (a) properties that won't change between postbacks (ID, CssClass...) as well as initial values for dynamic properties (which can then be modified by code in the rest of the page lifecycle - Load, event handlers, PreRender).

当在负载或preRender动态添加控件,ViewState是被跟踪。那么开发商可以控制哪些化子性质是持续了动态添加控件如下:

When dynamically adding controls in Load or PreRender, ViewState is being tracked. The developer can then control which propeties are persisted for dynamically added controls as follows:


  • 控制之前设置

    属性添加到页面的控件树不会被持久化到ViewState中。通常,您可以添加控件到控件树之前设置没有动态属性(身份证等)。

  • Properties set before the control is added to the page's control tree are not persisted to ViewState. You typically set properties that are not dynamic (ID etc) before adding a control to the control tree.

在控制后设置的属性添加到页面的控件树被保存到视图状态(ViewState的跟踪是从Load事件之前启用了preRender事件之后)。

Properties set after the control is added to the page's control tree are persisted to ViewState (ViewState tracking is enabled from before the Load Event to after the PreRender event).

在你的情况,你的preRender处理程序添加控件到页面的控件树之前设置属性。为了得到你想要的结果,加入控制控件树后,设置动态属性:

In your case, your PreRender handler is setting properties before adding the control to the page's control tree. To get the result you want, set dynamic properties after adding the control to the control tree: .

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2]        
    tempLink.ID = "valueLinkButton"; // Not persisted to ViewState
    Controls.Clear();
    Controls.Add(tempLink);
    tempLink.Value = "new value";  // Persisted to ViewState
    tempLink.Text = "Click";       // Persisted to ViewState
}