ASP.net WebForms - Constructor vs. Page_Load

I'm new to WebForms, I think I have a pretty simple question. I often see people initialize any dependencies in the page_load method of their class. Is this a common thing?

Things I usually write in the constructor.

How can I decide what belongs to the constructor and what fits better in the page_load processing method

+5
source share
1 answer

You should take a look at the asp.net life cycle .
In the costructor method, you can write a lot of code, declare variables, and use classes and libraries.
But if you need some asp.net elements ( Page , Controls , Session , QueryString , etc.), you must be in Page_Load or other lifecycle methods.

When an ASP.NET page starts, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instance management, restoration and maintenance of state, running event handler code, and rendering. It is important for you to understand the life cycle of a page so that you can write code at the appropriate stage in the life cycle for the effect that you intend to use. In addition, if you are developing custom controls, you should be familiar with the life cycle of the page in order to properly initialize controls, populate the control properties with view state data, and run any control behavior code. (The life cycle of the control is based on the life cycle of the page, but the number of events for the control increases on the page than is available for a single ASP.NET page.)

+6
source

Source: https://habr.com/ru/post/1215576/


All Articles