页面范围变量消失

时间:2012-07-26 09:00:36

标签: c# asp.net .net

假设我有以下asp.net页面:

public partial class SamplePage : System.Web.UI.Page
{
    private int UserID;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnSearchUser_Click(object sender, EventArgs e)
    {
       UserID = 5;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write(UserID.ToString());
    }
}

但UserID始终为0.如何实现它始终为5?

2 个答案:

答案 0 :(得分:2)

因为按钮的单击导致回发并且在回发期间数据总是丢失,因为HTTP协议是无状态的。所以你必须将该UserID存储到视图状态以保持其值...这就是为什么我们有State Mangement的Asp.net中的概念。 但是你可以像这样实现它......

public partial class SamplePage : System.Web.UI.Page
{
    int UserID;
  protected void Page_Load(object sender, EventArgs e)
  {

  }
 protected void btnSearchUser_Click(object sender, EventArgs e)
 {
    UserID=5;
    ViewState["UserID"] = UserID;
 }
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
    if(ViewState["UserID"]!=null)
    Response.Write(ViewState["UserID"].ToString());
 }
}

答案 1 :(得分:0)

要在回发之间保留数据,您需要将其置于当前控件的视图状态:

private int UserID
{
    get
    {
        return this.ViewState["UserID"] as int? ?? -1; // if data is missing, default value -1 will be returned
    }
    set
    {
        this.ViewState["UserID"] = value;
    }
}