ASP.Net 生命周期和数据库更新顺序
我一直在阅读有关页面生命周期的内容。我了解生命周期,但是,不清楚该做什么以及何时做。问题是我使用 Page_Load 来获取数据库值并设置表单字段。我使用按钮的 onClick 方法来更新数据库。但是,表单字段文本属性是在 Page_Load 期间设置的,因此实际上只是使用旧值更新数据库。
Page_Load:我收集数据,并设置控件文本属性以反映数据。 Button_onClick:我从表单更新数据库 问题:它正在更新从 Page_Load 收集的值,而不是实际的表单。
当然,我不应该在 Page_Load 中执行所有操作。那么我在这个过程中哪里出了问题呢?
I have been reading about the Page LifeCycle. I understand the LifeCycle, however, it's not clear on what to do, and when to do it. The problem is I use Page_Load to get database values, and set form fields. I use a button's onClick method to update the database. However, the form fields text properties were set during Page_Load, so it's really only updating the database with the OLD values.
Page_Load: I gather data, and set control text properties to reflect data.
Button_onClick: I update the database from the form
Problem: It's updating values gathered from Page_Load and not the actual form.
Certainly, I am not supposed to perform everything in the Page_Load. So where am I going wrong during this process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Page_Load
如果您要在 Page_Load 事件中加载数据库数据,首先要做的就是将其包装在
if (!IsPostBack)
语句中。http://msdn.microsoft.com/en -us/library/system.web.ui.page.ispostback.aspx
所以
IsPostBack = true
时页面循环就是回发的结果。在 Page_Load 中,您应该仅在
IsPostBack = false
时收集数据,而不是在每次页面加载时收集数据。设置字段
我个人更喜欢在 PreRender 事件处理程序上设置字段内容(但说实话,我不知道应该/必须在那里完成,这对我来说似乎更符合逻辑)。
PreRender 在回发事件(单击按钮、下拉选择更改...)之后执行,因此它确保在渲染页面之前完成更新和更一般的数据修改。
Page_Load
If you are loading your database data in the Page_Load event, the very first thing to do is to wrap it within a
if (!IsPostBack)
statement.http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
So
IsPostBack = true
when the page cycle is the result of postback.In your Page_Load, you should only gather your data when
IsPostBack = false
, not on every page load.Setting fields
I personnaly prefer to set the fields content on the PreRender event handler (but honnestly i don't know it should/must be done there, it just seems more logic to me).
PreRender is executed after your postback events (click on a button, drop-down selection change...) so it ensures that your updates and more generally data modifications are done before rendering the page.