当用户单击 asp.net Web 应用图像按钮时更新计数器



我有一个 ASP.NET Web 窗体应用程序,用户在其中打开 ImageButton 控件上的图像。在定义方法之前,我将全局 int 变量"计数器"设置为零。每次用户单击ImageButton控件时,"计数器"应该增加一个。与 ImageButton 关联的 OnClick 方法正在触发,但我认为每次单击后都会重置"计数器"。我知道这一点,因为只有 Image_Click 中的 if 分支被执行。如何确保每次点击都记住"计数器"的更新值?

以下是 ImageButton 的.aspx代码:

<asp:ImageButton ID="pic" runat="server" OnClick="Image_Click" />

下面是用于Image_Click的 c# 代码:

public int numClick++;
protected void Image_Click(object sender, ImageClickEventArgs e)
{
numClick++;
if (numClick % 2 == 1)
{
pos1x = e.X;
pos1y = e.Y;
labelarea.Text = " " + pos1x;
}
else if (numClick % 2 == 0)
{
pos2x = e.X;
pos2y = e.Y;
distx = Math.Abs(pos2x - pos1x);
disty = Math.Abs(pos2y - pos1y);
redistx = (int)(Math.Ceiling((float)(distx / (zoom * Math.Floor(dpiX / 4.0)))));
redisty = (int)(Math.Ceiling((float)(disty / (zoom * Math.Floor(dpiY / 4.0)))));
if (mode == 1)
{
if (distx >= disty)
{
lengthlabel.Text = "Length: " + redistx;
total += redistx;
}
else
{
lengthlabel.Text = "Length: " + redisty;
total += redisty;
}
labeltotal.Text = "Total: " + total;
}
}
}

您必须将点击计数存储在 Sesson 或视图状态中,因为它确实会在每次页面加载后重置。与应用程序不同,网站变量仅在页面执行的生命周期内存在。 下面是一个有关如何跨回发保留变量的简单示例。

protected void Image_Click(object sender, EventArgs e)
{
//create a variable for the clicks
int ButtonClicks = 0;
//check if the viewstate exists
if (ViewState["ButtonClicks"] != null)
{
//cast the viewstate back to an int
ButtonClicks = (int)ViewState["ButtonClicks"];
}
//increment the clicks
ButtonClicks++;
//update the viewstate
ViewState["ButtonClicks"] = ButtonClicks;
//show results
Label1.Text = "Button is clicked " + ButtonClicks + " times.";
}

最新更新