0

我正在尝试在 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 的值始终为 0。

4

1 回答 1

0

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

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

  • 将其保存在数据库中
  • 将其保存在应用程序对象中(这是所有用户共享的:

    // 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");
    
于 2013-05-11T18:21:50.980 回答