问题描述
我有一个相当复杂的页面,可以动态建立一个中继器内的用户控件。该中继器必须在初始化页面活动期间 ViewState中之前被绑定
初始化或动态创建的用户控件将不保留其状态。
I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before ViewState
is initialized or the dynamically created user controls will not retain their state.
这将创建一个有趣的第二十二条军规,因为我绑定中继器的需求对象在初始页面加载创建,然后坚持在内存中,直到用户选择离开或保存。
This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.
由于我不能使用的ViewState
来存储这些对象,但有它初始化期间可用,我不得不将其存储在会话。
Because I cannot use ViewState
to store this object, yet have it available during Init, I have been forced to store it in Session.
这也有问题,因为我必须明确地空以模拟如何的ViewState
工作在非回发会话值。
This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how ViewState
works.
必须有一个更好的办法在这种情况下状态管理。任何想法?
There has to be a better way to state management in this scenario. Any ideas?
编辑:关于使用一些好的建议 LoadViewState
,但我仍然有不被状态恢复的问题时,我这样做
Some good suggestions about using LoadViewState
, but I'm still having issues with state not being restored when I do that.
下面是有点如果页面结构
Here is somewhat if the page structure
首页 - >用户控件 - >转发器 - >动态地创建用户控件的施氮量
Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.
我把覆盖 LoadViewState
父用户控件
,因为它的设计是完全封装和独立的页它是。我想知道如果这是问题的所在。
I put the overridden LoadViewState
in the parent UserControl
, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is.
推荐答案
在页面上的LoadViewState方法是绝对的答案。这里的总体思路:
The LoadViewState method on the page is definitely the answer. Here's the general idea:
protected override void LoadViewState( object savedState ) {
var savedStateArray = (object[])savedState;
// Get repeaterData from view state before the normal view state restoration occurs.
repeaterData = savedStateArray[ 0 ];
// Bind your repeater control to repeaterData here.
// Instruct ASP.NET to perform the normal restoration of view state.
// This will restore state to your dynamically created controls.
base.LoadViewState( savedStateArray[ 1 ] );
}
SaveViewState需要创建我们在上面使用savedState数组:
SaveViewState needs to create the savedState array that we are using above:
protected override object SaveViewState() {
var stateToSave = new List<object> { repeaterData, base.SaveViewState() };
return stateToSave.ToArray();
}
不要忘了也结合在初始化中继器或使用code这样的负荷:
Don't forget to also bind the repeater in Init or Load using code like this:
if( !IsPostBack ) {
// Bind your repeater here.
}
这篇关于你是做什么的时候,你不能使用ViewState的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!