Reputation: 1016
I am creating an asp.net page which loads data from a (SQL) visual studio database file (.mdf).
The data is loaded into a list of User objects (List) which contain the user data obtained from the database. This data is then displayed in a ASP.net table with a check box in column one. This allows the person viewing the webpage to in theory select users via the check boxes.
I have an ASP.net button also on the same page which when clicked will cause a post-back and go through the table row's and correctly identify which rows have and have not been checked. I am able to get the user data at this point as the Page_Load event is fired and the database contents are re-loaded for the second time.
Obviously this could become quite expensive obtaining the full list of users on each Page_Load so I have started investigating using the IsPostBack variable which allows me to identify whether it is a button click or standard page load.
The problem I have when using IsPostBack is the database contents loaded into the List on the initial Page_Load event would now be equal to null as the call into the database would never occur. This is understandable expected behavior and my question is what would be the best way to preserve the contents of the list so the button click can access the data loaded from the database on the initial Page_Load, without having to do another database query?
Thanks.
Upvotes: 1
Views: 1625
Reputation: 5773
How about keeping a private variable inside your class?
private List<myObject> _data = null;
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
_data = loadDataFromDb();
}
}
private void Button_Click()
{
if(_data != null)
//Do something with the data
}
-Updated: I think you can avoid postbacks this way, so you only load your data once.
Upvotes: 0
Reputation: 16144
If its not user specific data that you are taking about store it in Cache.
If its use specific data store it in session.
Upvotes: 1
Reputation: 5679
I would suggest caching the result from the database and then doing your binding as usual. There are other options such as storing it in the ViewState but that can lead to much bigger page sizes depending on the data (personally I'm not a fan of ViewState, but it is an option).
At the end of the day, there is a certain amount of data you need to make the page work, you can't get away from having to store & retrieve that data somehow, so it comes down to deciding what is the most maintainable (and expected) way that doesn't have unacceptable tradeoffs. In my opinion that would be caching the database result, but it really depends on the application.
Upvotes: 1