Update counter when user clicks an asp.net web app imagebutton

[亡魂溺海] 提交于 2019-12-11 15:58:08

问题


I have an ASP.NET web forms application where the user opens up an image on an ImageButton control. I set a global int variable "counter" to zero outside before defining methods. Every time the user clicks on the ImageButton control the "counter" is supposed to increase by one. The OnClick method associated with the ImageButton is firing, but I think the "counter" is being reset after each click. I know this because only the if branch in Image_Click is being executed. How can I make sure that the updated value of "counter" is remembered for each click?

Here is .aspx code for ImageButton:

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

Here is c# code for Image_Click:

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;
        }
    }
}

回答1:


You have to store the click count in a Sesson or Viewstate because it is indeed reset after each page load. Unlike apps, a website variables only exists during the life op the page execution. Below a simple example of how to persist a variable across PostBack.

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.";
}


来源:https://stackoverflow.com/questions/52560999/update-counter-when-user-clicks-an-asp-net-web-app-imagebutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!