ASP.NET 在 OnPreInit 之前处理按钮单击事件
我有一个数据访问层、一个业务逻辑层和一个表示层(即页面本身)。
我处理 OnPreInit 事件并填充页面所需的集合。所有数据都来自 SQL Server 数据库,我不使用缓存。
我处理按钮单击事件以从表单中获取值并将新对象插入数据库中。问题是,当我处理单击事件时,集合已经被填充,因此尚未检索已插入数据库的新项目。
对此可接受的解决方案是什么?
我可以将新对象直接插入到集合中并重新绑定 GridView,但 SQL 查询仅选择一组对象,并且新对象可能会落在该组之外。
谢谢!
I have a data access layer, a business logic layer and a presentation layer (ie. the pages themselves).
I handle the OnPreInit event and populate collections required for the page. All the data comes from an SQL server database and I do not use caching.
I handle a button click event to grab values from a form and insert a new object into the database. The problem is that by the time I handle the click event, the collections have already been populated, so the new item which has been inserted into the database has not been retrieved.
What is the accepted solution to this?
I could insert the new object directly into the collection and re-bind the GridView, but the SQL query selects only a set of objects and the new object could fall outside of this set.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我通常在页面中的两个位置进行数据绑定:
在 Page_Load 内部,如果 !IsPostBack 加载初始状态。
作为事件处理程序中的最后一行之一,显示添加/编辑/删除记录的结果。
作为事件处理
您遇到的问题只是使用 OnPreInit 进行数据绑定的结果,因此您可能必须停止这样做,或者尝试其他人建议的次优方法之一(重定向回回发后的页面)。
I generally do databinding in two places in my pages:
Inside Page_Load, if !IsPostBack to load the initial state.
As one of the last lines in event handlers to show the result of adding/editing/deleting a record.
The issue you're running into is just the result of using OnPreInit to do data binding, so you're probably going to have to stop doing that, or try one of the sub-optimal approaches that others have suggested (redirecting back to the page after a postback).
稍后在页面生命周期中执行数据绑定操作,例如在处理任何控件事件后触发的页面 PreRender 事件中。
Perform your data binding operations later in the page lifecycle, e.g. in the page PreRender event which fires after any control events have been handled.
您应该只处理点击事件。然后在数据库更新/插入后,您必须重新绑定数据。根据您的实施情况,您可能需要重新发布页面。如果您要使用普通的数据绑定,您只需再次调用绑定方法即可。
You should just handle the click event. Then after your database update/insert, you must rebind your data. Depending upon your implementation, you might need to re-post the page. If you were to use normal data binding you could just call the bind method again.
您可以使用此方法来确定在 PreInit 中哪个控件发出回发:http://blogs.microsoft.co.il/blogs/gilf/archive/2010/03/01/discover-which -control-raised-a-postback.aspx
You could use this method to determine which control issued the postback in the PreInit: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/03/01/discover-which-control-raised-a-postback.aspx