3

我正在 ASP.NET 中编写一个页面,并且在回发初始化周期之后遇到问题:

我有(类似于)以下内容:

public partial class MyClass : System.Web.UI.Page
{
    String myString = "default";

    protected void Page_Init(object o, EventArgs e)
    {
        myString = Request["passedString"];
        //note that I've tried to set the default here in Init on NULL...
    }

    protected void Page_Load(object o, EventArgs e)
    {
         if(!Postback)
         {
             //code that uses myString....
         }
         else
         {
            //more code that uses myString....
         }
    }
}

发生的事情是我的代码很好地拾取了“passedString”,但由于某种原因,在回发时,它重置为默认值 - 即使我将默认值的分配放在 Page_Init 代码中......这让我想知道怎么回事。。

有什么帮助吗?

4

2 回答 2

4

一旦响应发送到浏览器,您的类成员变量就不会继续存在。尝试改用 Session 对象:

public partial class MyClass : System.Web.UI.Page
{    

    protected void Page_Init(object o, EventArgs e)
    {
        Session["myString"] = Request["passedString"];
        //note that I've tried to set the default here in Init on NULL...
    }

    protected void Page_Load(object o, EventArgs e)
    {
         string myString = (string) Session["myString"];

         if(!Postback)
         {
             // use myString retrieved from session here
         }
         else
         {
            //more code that uses myString....
         }
    }
}
于 2009-03-27T16:34:25.553 回答
3

我感觉到你的痛苦,马特。不久前我问了一个类似的问题:

要进一步了解页面生命周期,请查看以下问题:ASP.NET WebForm 的“页面生命周期”是什么?

于 2009-03-27T16:29:41.103 回答