Skip to main content
 首页 » 编程设计

c#之Visual Studios C#之页面刷新时重新调用类

2024年01月25日40www_RR

在 Visual Studio 中,是否每次刷新页面时都会调用该类?我有以下类(class) - 我想在每次单击按钮时向变量添加值;

public partial class _Default : System.Web.UI.Page 
{ 
    Random random = new Random(); 
    int total; 
    int playerTotalValue; 
 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 
    protected void ranPlayer_Click(object sender, EventArgs e) 
    { 
        int randomNumTwo = random.Next(1, 10); 
        playerTotalValue = playerTotalValue + randomNumTwo; //playerTotalValue gets reset to zero on every click 
        playerTotal.Text = playerTotalValue.ToString(); 
    } 
} 

每次我点击“ranPlayer”按钮时,playerTotalValue 都会重置为零,或者这就是我认为发生的情况。

请您参考如下方法:

HTTP 是无状态的。这意味着它不会像在 Windows 窗体编程中那样保留变量中的值。因此,每当您单击按钮时,它的执行方式与初始页面加载时的加载方式相同。可是等等 !。您在文本框中有可用的值。因此,您可以从那里读取值并将其存储在变量中。

    protected void ranPlayer_Click(object sender, EventArgs e) 
    { 
        playerTotalValue =0; 
        if(!String.IsNullOrEmpty(playerTotal.Text)) 
        { 
          playerTotalValue =Convert.ToInt32(playerTotal.Text); 
        } 
        int randomNumTwo = random.Next(1, 10); 
        playerTotalValue = playerTotalValue + randomNumTwo; //playerTotalValue gets reset to zero on every click 
        playerTotal.Text = playerTotalValue.ToString(); 
     }