我正在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代码中放置了默认值…这使我想知道发生了什么……
有帮助吗?
解决方法
响应发送到浏览器后,您的类成员变量不会生效.请尝试使用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.... } } }