0

假设我有以下 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?

4

2 回答 2

2

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

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());
 }
}
于 2012-07-26T09:10:50.193 回答
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;
    }
}
于 2012-07-26T09:13:45.597 回答