c# - 用户控件不保留私有(private)值,返回Page_Load中设置的值

标签 c# asp.net user-controls

我有一个定义如下的控件:

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();

在此方法中,检查 ControlIDtable 显示它们仍然分别为 0 和一个空的 DataTable

为什么 ControlIDtable 不保留在 SetControlID 方法中设置的值?

编辑:删除 2 变量的静态属性没有任何区别。

编辑 #2: 我只想指出,我已经在许多其他页面中使用了这种方法,并且一切正常。这个有什么不同?

最佳答案

在 ASP.NET 中,Page 类的生命周期是指处理请求的持续时间。那就是当请求进来时,页面的类被实例化, View 状态被反序列化以恢复状态(如果它是回发),一个事件被运行(比如按钮点击),响应生成,然后对象被销毁。因此,任何未将其状态保存到 View 状态(例如 int)的成员都不会在激活过程中保留。

此外,您的代码中的一个疑点是 ControlID 和 tabe 都被声明为静态的。这意味着这些值将在页面的所有调用者之间共享(并且每次请求新页面时,所有用户的表都将被覆盖)。这似乎不对。

关于c# - 用户控件不保留私有(private)值,返回Page_Load中设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934481/

相关文章:

c# - 使用静态记录器、静态帮助程序类进行依赖注入(inject)

c# - 请求的资源正在使用中。 (来自 HRESULT : 0x800700AA) - Microsoft WebView 的异常

javascript - ASP.NET 用户控件中的 jQuery

c# - 如何使用 Ninject 泛型将接口(interface)绑定(bind)到类?

c# - 如何从用户控件页面的代码后面找到 ListView 的 ItemTemplate 中的控件?

.net - WPF MVVM + UserControl 与后面的代码

c# - 在 ASP.NET 网站中保持应用程序状态

c# - LINQ 按多个字段分组 - 语法帮助

c# - 使用列表查询数据库

asp.net - 有没有人设法让 OpenXml 与 dnx core 5 一起工作?