开发者

ASP.NET handling button click event before OnPreInit

开发者 https://www.devze.com 2022-12-24 11:53 出处:网络
I have a data access layer, a business logic layer and a presentation layer (ie. the pages themselves).

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!


I generally do databinding in two places in my pages:

  1. Inside Page_Load, if !IsPostBack to load the initial state.

  2. 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).


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.


  1. Retrieve data on the Page.LoadComplete event and do a data bind.
  2. If for some reason, should retrieve them only on PreInit, then retrieve them on for !IsPostBack condition and bind them and for PostBack conditions, handle them on LoadComplete


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

0

精彩评论

暂无评论...
验证码 换一张
取 消