如何在回发后保留变量值

时间:2016-11-06 00:54:57

标签: asp.net

我试图在回发后保留变量值。我通过会话变量和Viewstate尝试了它,但未能保持随机数的值相同。每次按下按钮后(页面刷新后)我都会得到一个新的随机值,但我希望保持相同的值。

//in code behind
public static int RandNumber{ get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    //by using session 
    Session["rand"] = rnd.Next(0, 10);
    RandNumber = Int32.Parse(Session["rand"].ToString());

    //by view state
    int rand = rnd.Next(0, 10);
    ViewState["KEY"] = rand;
    RandNumber = Int32.Parse(ViewState["KEY"].ToString());
}

以表格形式发回:

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

并尝试在页面中访问如下:

<p>Random No: <%= RandNumber %></p>

1 个答案:

答案 0 :(得分:4)

只有通过检查IsPostBack

才能设置一个新的随机数
while (score < 0 || score > 100) 
 {
   System.out.println("please enter a number between 0 and 100.");

        while(!scan.hasNextInt())
        {
             scan.next();
        }
      score = scan.nextInt();
  }