【问题标题】:How to maintain class after button click on page按钮单击页面后如何维护类
【发布时间】:2020-02-21 08:36:35
【问题描述】:

我在 ASP .NET 中有一个页面,当我访问它时,我以编程方式在 TextBox 中设置了一个值。当我单击按钮时,我想更新该值,但它给了我错误:

对象未定义

这是我的代码:

public partial class InsertValues : System.Web.UI.Page
    {
        DataProvider dataProvider = new DataProvider(); // This class contains all the querys I need to pull data

        public MyValuesClass myValues; // This is my class where I get the data from my DB

        protected void Page_Load(object sender, EventArgs e)
        {   
            if (!IsPostBack)
            {      
                startMyPage();  // Function that gets the values from the DataBase and sets my TextBox with the values.
            }
            else
            {

            }
        }

private void startMyPage()
        {
            myValues = dataProvider.getValuesFromDB(); // Function that gets the values from a query and put them in my class, the values are. String "Banana" and Bool isNew = True

            if (!myValues.isNew) // 
            {
                txtFood.Text = myValues.food
            }
            else
            {
                myValues= new myValues();
                myValues.isNew = true;
            }
        }

protected void btnSave_Click(object sender, EventArgs e)
        {
            if (myValues.isNew) // Object not defined. 
            {
                 dataProvider.addMyValues(myValues); // It Inserts into my DB
            }
            else
            {
                 dataProvider.editMyValues(myValues); // It Updates into my DB
            }
        }
    }

基本上,在我单击“btnSave”后,类 myValues 变为 null,并且我收到错误 Object not defined,有没有办法维护该类价值观?

【问题讨论】:

    标签: asp.net webforms buttonclick


    【解决方案1】:

    您需要在 PostBack 上重新获取您的 myValues 对象。

    protected void Page_Load(object sender, EventArgs e)
    {   
        if (!IsPostBack)
        {      
            startMyPage();
        }
        else
        {
            myValues = dataProvider.getValuesFromDB();
        }
    }
    

    只有存储在 ViewState 或等效持久性机制中的数据才会在初始页面加载和回发之间保留,这就是为什么你的 webforms 页面控件的值会被持久化,但你的代码隐藏属性不会。

    您可以像这样在 ViewState 中手动存储内容:ViewState["someKey"] = someObject;,但 someObject 必须是可序列化的。看起来 myValues 是一个 ORM 对象,所以它可能是不可序列化的。

    【讨论】:

    • 是的,我错过了这部分,非常感谢。关于只有存储在 ViewState 或等效持久性机制中的数据才会在初始页面加载和回发之间保留,我只想问你一件事我想了解更多信息,你能给我一个链接?会很棒的。
    • 乐于助人。我没有任何具体的链接。尝试在 ASP .NET WebForms、ViewState 和 ASP .NET Sessions 中搜索持久化数据。
    【解决方案2】:

    所有变量都会在每次回发时重新启动。您最好将您的类 public MyValuesClass myValues 存储在会话或视图状态中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多