计算按钮点击动态生成的按钮

时间:2016-06-22 05:00:18

标签: c# asp.net button

在C#中计算在同一页面中点击asp网络按钮多少次的简单方法,例如page1.aspx?计数器应该对每个用户有效并在我转到page2.aspx时重置,然后返回到page1.aspx。如果重新加载同一页面,计数器应该保持不变。 该按钮是在Page Init中动态创建的 Button x = new Button(); 我不能使用javascript。感谢

2 个答案:

答案 0 :(得分:0)

为维护点击计数器创建一个类

public static class Counter
{
       private static long hit;

       public static void HitCounter()
       {
          hit++;
       }

       public static long GetCounter()
       {
          return hit;
       }
}

在页面加载事件

处增加计数器的值
protected void Page_Load(object sender, EventArgs e)
{
    Counter.HitCounter(); // call static function of static class Counter to      increment the counter value
}

您重定向用户的时间可以计为null

答案 1 :(得分:0)

使用session的更好方法是,当用户在Web应用程序中导航ASP.NET页面时,它使您能够为用户存储和检索值。这样即使从page2.aspx返回,您也可以访问该值。这个代码将是

protected void button_Click(object sender, EventArgs e)
{
   if(Session["ClickCount"]!=null)
       Session["ClickCount"]=(int)Session["ClickCount"]++;
   else
       Session["ClickCount"]=0;
}

如果您想在离开页面时重置它,则意味着您可以使用:

 if(Session["ClickCount"]!=null)
       Session["ClickCount"]=0;
 // Redirect to page