2013-08-23 28 views
1

我有以下的測試ASP頁:做asp頁面變量不會持久嗎?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
     <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> 
    </div> 
    </form> 
</body> 
</html> 

用下面的代碼背後:

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

    int x = 0; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     Label1.Text = x.ToString(); 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     x++; 
     Label1.Text = x.ToString(); 
    } 
} 

從非web編程的心態我本來以爲int x本來是一種對象場對於測試頁類,當我做x++x的價值會持續通過回發,但它似乎並非如此。那麼這些領域究竟如何在持久性方面發揮作用呢?我覺得很奇怪,因爲當你點擊按鈕時,Label1.Text會在第一次點擊它時變爲1,但是在此之後你無法獲得1。

然後,當我明白爲什麼會發生這種情況時,最簡單的方法是什麼? (中x值在回發仍然存在)

這是它看起來像現在使用的ViewState這正是我一直在尋找:

公共部分類測試:System.Web.UI.Page {

//static int x = 0; 



protected void Page_Load(object sender, EventArgs e) 
{ 

    if (ViewState["x"] == null) 
    { 
     ViewState["x"] = 0; 
     Label1.Text = ViewState["x"].ToString(); 
    } 


    //Label1.Text = x.ToString(); 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 

    ViewState["x"] = Convert.ToInt32(ViewState["x"].ToString()) + 1; 
    Label1.Text = ViewState["x"].ToString(); 
    //x++; 
    //Label1.Text = x.ToString(); 
} 

}

+0

抱歉,我認爲這可能是http://stackoverflow.com/questions/7534946/are-public-properties-in-an-asp的副本-net-code-behind-supposed-to-persist-between-page?rq = 1或多或少>< – chilleo

回答

4

x將不會被保留。在每次請求時,x將被初始化爲0.

使用例如會話狀態來存儲例如x的值,例如, Session["x"] = x;

至於標籤文本,ASP.NET將存儲在ViewState的內部,它保存每個請求的控制值。如果要存儲僅在一個頁面上使用的值,則可以自己使用ViewState。如果您希望網站中其他網頁上的值可用,請使用會話。

ViewState["x"] = x;

+0

Viewstate就是我一直在尋找的東西。完全忘記了手動操作視圖狀態。謝謝! – chilleo

0

像PHP,ASP可以使用會話變量和cookie來存儲持久性數據。但是,如果您只使用腳本變量,則每次運行腳本時都會重新初始化它們。

你也可以使用靜態變量,它們表現更好,但我認爲存在安全風險。

0

正如傑森埃文斯正確指出..你必須存儲在Session中的價值,以堅持下去。你可以做到以下幾點:

protected void Page_Load(object sender, EventArgs e) 
    { 
     //Label1.Text = x.ToString(); 
     Session["x"] = x; 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     x = Session["x"]; 
     x++; 
     Label1.Text = x.ToString(); 
    } 

Ofcourse有堅持像餅乾,ViewState中值的其他方式,增加查詢字符串等,但這些之中,SessionState的是最常用的。

1

如果您希望您的變量x在每個回帖之間保持不變,然後將其存儲在會話或Cookie中,並在每封回帖中將其恢復。 請不要使用由Samiey Mehdi發佈的static,因爲這將使所有Web會話與應用程序域相同。

你可以將其存儲在諸如會話:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if(!Page.IsPostBack) 
      Session["X"] = x; 
     int valueFromSession = Convert.ToInt32(Session["X"]); 
     Label1.Text = valueFromSession.ToString(); 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     int valueFromSession = Convert.ToInt32(Session["X"]); 
     valueFromSession++; 
     Session["X"] = valueFromSession; 
     Label1.Text = valueFromSession.ToString(); 
    }