我正在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....
}
}
}
正在发生的事情是我的代码选择了“passString”就好了,但出于某种原因,在回发时,它会重置为默认值 - 即使我在Page_Init代码中放置了默认值...这让我想知道发生了什么......
任何帮助?
答案 0 :(得分: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....
}
}
}
答案 1 :(得分:3)
我觉得你的痛苦马特。我不久前问了一个类似的问题:
要进一步了解页面生命周期,请查看此问题:What is the 'page lifecycle' of an ASP.NET WebForm?