asp.net - 按钮单击页面后如何维护类
问题描述
我在 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,有没有办法维护类值?
解决方案
您需要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 对象,所以它可能不是可序列化的。
推荐阅读
- ios - XCODE:iPhone 12 的尺寸将如何影响约束和情节提要?
- mysql - 计算来自同一列mysql的时间戳之间的时间差(以分钟为单位)
- c++ - 为什么要从“Class”转换为“Class*”?
- python - 跨多个字典键的交集
- ios - Flutter - FCM 远程/静音通知(后台应用)
- yocto - Yocto - glib-gettextize:未找到
- python - 如何执行矩阵并集和交集?
- javascript - 如何测试已在 React 中从子组件提升到父组件的状态?
- sql-server - 您如何衡量索引对表写入的影响?
- html - CSS Custom spinner using letter "D"