我有一个定义如下的控件:
public partial class MyControl: System.Web.UI.UserControl
{
static int ControlID;
static DataTable table;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ControlID = 0;
table= new DataTable();
}
}
public void Save()
{
//ControlID is 0
//table is empty DataTable
}
public void SetControlID(int id)
{
ControlID = id; //This DOES set id correctly
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(SelectCommand, conn);
command.Parameters.AddWithValue("@ControlID ", ControlID);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
//table is correctly filled with the correct data
}
}
此控件被添加到我的 aspx
页面,如下所示:
<uc:MyControl ID="myCont" runat="server" />
在 Page_Load
中调用:
myCont.SetControlID(1); //This correctly calls the `SetControlID` method and
//seems to fill the `table` and set `ControlID` to 1.
但是页面上有一个“保存”按钮调用:
myCont.Save();
在此方法中,检查 ControlID
和 table
显示它们仍然分别为 0 和一个空的 DataTable
。
为什么 ControlID
和 table
不保留在 SetControlID
方法中设置的值?
编辑:删除 2 变量的静态属性没有任何区别。
编辑 #2: 我只想指出,我已经在许多其他页面中使用了这种方法,并且一切正常。这个有什么不同?
最佳答案
在 ASP.NET 中,Page 类的生命周期是指处理请求的持续时间。那就是当请求进来时,页面的类被实例化, View 状态被反序列化以恢复状态(如果它是回发),一个事件被运行(比如按钮点击),响应生成,然后对象被销毁。因此,任何未将其状态保存到 View 状态(例如 int)的成员都不会在激活过程中保留。
此外,您的代码中的一个疑点是 ControlID 和 tabe 都被声明为静态的。这意味着这些值将在页面的所有调用者之间共享(并且每次请求新页面时,所有用户的表都将被覆盖)。这似乎不对。
关于c# - 用户控件不保留私有(private)值,返回Page_Load中设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934481/