用户控制在Postback中丢失Viewstate

我有一个用户控件,它使用对象作为内部属性(下面是一些代码)。

我在以编程方式设置Step类的属性时遇到问题,当以编程方式设置时,它会在回发时丢失,这表明与Viewstate(?)有关。

以声明方式设置Step类的属性时,它工作正常。

有没有人对这个代码是什么/什么导致它在回发中失去状态有任何想法?

ASPX

   

ASPX代码背后

  protected void btnGoToStep2_OnClick(object sender, EventArgs e) { StepControl1.Step1.StatusText = "4 Products Selected"; } protected void btnBackToStep1_OnClick(object sender, EventArgs e) { // StatusText (of Step1) gets lost at this point. } 

用户控制代码背后

 public partial class StepControl : System.Web.UI.UserControl { [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [NotifyParentProperty(true)] public Step Step1 { get; set; } [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [NotifyParentProperty(true)] public Step Step2 { get; set; } protected void Page_Init(object sender, EventArgs e) { AddSteps(); } private void AddSteps() { } } [Serializable()] [ParseChildren(true)] [PersistChildren(false)] public class Step { [PersistenceMode(PersistenceMode.Attribute)] public string Title { get; set; } [PersistenceMode(PersistenceMode.Attribute)] public string Status { get; set; } [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateInstance(TemplateInstance.Single)] [TemplateContainer(typeof(StepContentContainer))] public ITemplate Content { get; set; } public class StepContentContainer : Control, INamingContainer { } } 

我认为你设置的字符串永远不会进入ViewState。 我在这里的术语有点缺(读:我不知道术语)但我认为你的属性[PersistenceMode(PersistenceMode.Attribute)]只告诉ASP.NET它应该在标记中寻找一个名为“Status”的属性( ASPX文件)如果找到一个,将属性Status设置为其值(实际上我想知道它在你的示例中的确切位置?)。 它并没有告诉任何人把东西放到ViewState中。

如果您要沿着这些行定义属性Status

 [PersistenceMode(PersistenceMode.Attribute)] public string Status { get { object o = ViewState["Status"]; if(o != null) { return (string)o; } return string.Empty; } set { ViewState["Status"] = value; } } 

你应该过得更好

对于其余部分,我不确定您是否必须在UserControls中调用TrackViewState() ,甚至覆盖SaveViewStateLoadViewState但我不这么认为。 如果是这种情况,以下链接可能会有所帮助:

  • Microsoft: 了解ASP.NET视图状态
  • ASP.NET论坛: 如何在用户控件中保留ViewState

它可能与页面中控件创建的顺序有关。 如果在回发之后,控件的创建顺序与第一次加载页面的顺序不同,则retreate viewstate将不适用于这些控件。

如何以编程方式设置步骤的属性?