未能加载视图状态(Failed to load ViewState),解决之道

在动态加载页面(用户控件)的时候,我的项目是利用atlas的UpdatePanel加载用户空间到PlaceHolder中,很容易出现这个错误:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. 
 

这个错误的原理如下:

在页面回传,重新生成时,会自动装入回传前的视图状态。结合自己的实验,了解的这个过程大致如下:

Init事件 -> ViewState加载 -> Load事件 -> 其它页面事件(如回传前的按钮点击)-> PreRender事件

用户控件动态加载代码通常都位于Load事件中(比如我的BindData),或者位于atals的Triger空间EventHandler中,此时整个页面的ViewState已经加载,就又通过一个有人称做Catch-up的机制再向PlaceHolder中新加载的控件追加其ViewState,而这个ViewState为回传前在相应位置的控件的ViewState。所以如若新的控件与旧的类型控件不同的话,将出现前述错误。

这个错误解决起来也很简单:

在加载新的空间之前,先加载一下原来的控件,然后把PlaceHolder Clear掉,然后加载新的控件,至于如何保存原来的控件信息,当然也是使用一个ViewState Property, 比如我的代码中的ControlType了!

 

         protected
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值