Server.Transfer丢失局部变量

时间:2011-10-26 17:16:45

标签: asp.net vb.net

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

一旦我的“目标”页面完全加载,我执行回发后,我对源页面对象的本地深度克隆会突然从内存中释放出来吗?这是设计 - 与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会停止与源页面的任何关联。

是否有更好的跨页对象传递方式?

1 个答案:

答案 0 :(得分: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标记。有人可以自由转换。