Asp.net失去了变量值

时间:2013-05-11 18:15:56

标签: asp.net variables

我正在尝试在ASP.NET中编写我的第一个WebApplication。这是我的代码:

Public Class WebForm2
Inherits System.Web.UI.Page
Public n As Integer
Public zetony As Integer
Public liczba As Boolean
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub
Private Function TextBox1_Validate(Cancel As Boolean)
    If Not IsNumeric(TextBox1.Text) Then
        MsgBox("Prosze podaj liczbe dobry uzytkowniku :)", vbInformation)
        Cancel = True
    Else : Cancel = False
    End If
    Return Cancel
End Function
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    liczba = TextBox1_Validate(liczba)
    If (liczba = False) Then
        n = Convert.ToInt32(TextBox1.Text)
        Label2.Text = n
    End If
End Sub
Protected Sub graj()
    Label2.Text = n
End Sub
Protected Sub Image1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click
    If zetony < 2 Then
        n -= 1
        ImageButton1.ImageUrl = "red_coin.gif"
        zetony += 1
    End If
End Sub

Protected Sub Image2_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton2.Click
    If zetony < 2 Then
        n -= 1
        ImageButton2.ImageUrl = "red_coin.gif"
        zetony += 1
    End If
End Sub

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    graj()
End Sub
End Class

我的问题是,只有在Button1_Click上我得到了适当的值。当我尝试调用Sub graj()时,n的值是alwayes 0.

1 个答案:

答案 0 :(得分:0)

HTTP是无状态的。这意味着对于每个请求,都会创建类WebForm2的新实例。因此,如果您在Button1_Click中设置n的值,则从Button2_Click访问它时将不会保留它,因为它是一个不同的实例。

要跨请求保存数据,有几种可能性,仅举几例:

  • 将其保存在数据库中
  • 将其保存在Application-object中(这是在所有用户之间共享:

    // setting the value
    HttpContext.Current.Application("n") = "somevalue";
    
    // Getting the value
    string test = HttpContext.Current.Application("n");
    
  • 将其保存在会话状态(这是在一个用户的所有请求中共享):

    // setting the value
    HttpContext.Current.Session("n") = "somevalue";
    
    // Getting the value
    string test = HttpContext.Current.Session("n");