2011-10-26 38 views
2

对于我的申请,我通过Server.Transfer有一个页面重定向到另一个页面(在同一应用程序内)。我需要这样做,因为原始页面有一个对象,我需要通过使用Page.PreviousPage属性来访问。失去Server.Transfer的局部变量

一旦我的“目的地”页面已经被完全加载,我所做的源页面的对象的本地深克隆突然从内存中释放一次我执行回发?这是由设计 - 与Server.Transfer有关吗?

一个例子...

Page1.aspx的:

Public Structure myCustomObject 
    Implements ICloneable 
    Dim someField as String = "default value" ' Default value 
    Public Function Clone() As Object Implements System.ICloneable.Clone 
     Dim temp as new myCustomObject 
     temp.someField = Me.someField 
     Return temp 
    End Function 
End Structure 

Dim obj As myCustomObject 
Public ReadOnly Property objProp as myCustomObject 
    Get 
     Return obj 
    End Get 
End Property 
objProp.someField = "changed value from source page" 

Server.Transfer("page2.aspx", True) 

Page2.aspx:

(onLoad) 
Dim newObj As myCustomObject 
newObj = Page.PreviousPage.objProp.Clone() 
Debug.Write(newObj.someField) ' Output: "changed value from source page" 

在这一点上,一切正常,因为它应该。东西克隆正确,一切都很好。

(Let's say this is on a button click event) 
Debug.Write(newObj.someField) ' Output: "default value"<- This is NOT "changed value from source page" for some reason when it was working literally a few lines ago! 

这是我在这里,我得到的问题。我的猜测是Server.Transfer在加载新页面后会停止与源页面的任何关联。

是否有跨页物体通过更好的办法?

+0

如果你把一个按钮和页面上的服务器端点击可以从点击事件访问对象?你能显示一些代码吗? –

+0

我所说的可能有点不清楚,但我不知道有任何其他方式来表达它。 – danyim

+1

这对我来说味道不好。当然,您可以将原始对象存储在其他容器中,并在重定向页面的页面加载中将其拉回。 – Graham

回答

2

只是传递一个变量在HttpContext,你将不得不处理你的施法,不知道什么Page.PreviousPage是:

当前页:

HttpContext CurrContext = HttpContext.Current; 
CurrContext.Items.Add("PreviousPage", Page.PreviousPage); 

转移到页面:

HttpContext CurrContext = HttpContext.Current; 
var previousPage = CurrContext.Items["PreviousPage"]; 

对不起,C#,有没有代码,当我回答时,问题没有用VB.NET标记。有人可以随意转换。

+0

这是否适用于对象?如果我走这条路线,我不需要序列化吗? – danyim

+0

Server.Transfer不是一个新的请求,你仍然在服务器上,不需要序列化。 HttpContext.Items只是一个Dictionary。 –

+0

我刚测试过你的方法,它给了我和我的例子相同的结果。不知何故,当我执行回发时,传输到页面的HttpContext.Current没有回忆我从当前页面添加的内容。 – danyim