Asp.net 丢失变量值 [英] Asp.net losing values of variables

查看:35
本文介绍了Asp.net 丢失变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ASP.NET 中编写我的第一个 Web 应用程序.这是我的代码:

I am trying to write my first WebApplication in ASP.NET. Here is my code:

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.

My problem is that, only on Button1_Click I got proper value. When I try to call Sub graj() value of n is alwayes 0.

推荐答案

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

HTTP is stateless. This means that for every request a new instance of the class WebForm2 gets created. So if you set the value of n inside Button1_Click it will not be preserverd when you access it from Button2_Click since it's a different instance.

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

To save your data across requests there are several possibilities, to name a few:

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

  • Save it in a database
  • Save it in the Application-object (this is shared across all users:

// setting the value
HttpContext.Current.Application("n") = "somevalue";

// Getting the value
string test = HttpContext.Current.Application("n");

  • 将其保存在会话状态中(这在一个用户的所有请求中共享):

  • Save it in the session-state (this is shared across all requests for one user):

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

  • 这篇关于Asp.net 丢失变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆