w0051977
w0051977

Reputation: 15807

Page.Load runs every time and takes too long

I have an ASP.Net page like this:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    'Page load code here.  Call Service Layer, which calls Business Layer.
End Sub

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
    'Button code here
End Sub

The code in the Page_Load takes too long because it has to connect to lots of different databases (code contained in Business Layer). What is the best way to cache the page so that the code in Page_Load does not run before the click event? The code in Page_Load is required as it generates the controls. Button1_Click loops through these controls.

I tend to focus on the Business Layer and Data Layer. I realize this is probably a basic question.

Upvotes: 0

Views: 1238

Answers (2)

Greg Bair
Greg Bair

Reputation: 669

If the information generated in Page_Load is not needed, you can simply put this line in there, at the top of the method (in C#, but I assume it's similar in VB):

If Page.IsPostback Then
    Return
End If

If, however, it is needed, then you can use the ViewState property of the Page object

I would use the method shown in the first example of the link above, and store the results of any calculations you need in there, and then use that to populate controls.

Upvotes: 0

mason
mason

Reputation: 32694

Page_Load will ALWAYS run before the click event. You need to familiarize yourself with the ASP.NET page lifecycle model and how postbacks work.

Most of the code that runs in Page_Load shouldn't run again on postback, so you use an if statement to check if it's postback. Most loading of controls etc will update the viewstate and so it wont be necessary to reinitialize those on postback.

Upvotes: 3

Related Questions