首页 > 解决方案 > 按钮单击页面后如何维护类

问题描述

我在 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类变为空,并且出现错误Object not defined,有没有办法维护类值?

标签: asp.netwebformsbuttonclick

解决方案


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

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

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

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


推荐阅读