单击页面后如何保持课程状态

问题描述 投票:0回答:2

我在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,有没有办法维护类Values?

asp.net webforms buttonclick
2个回答
1
投票

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

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

只有在ViewState或等效的持久性机制中存储的数据才会保留在初始页面加载和回发之间,这就是为什么Webforms页面控件的值得以保留,而属性后面的代码则不保留的原因。

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


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.