Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should stuff be done in an ASP.NET page?

I'm very new to ASP.NET and, after beating my head on a few problems, I'm wondering if I'm doing things wrong (I've got a bad habit of doing that). I'm interested in learning about how ASP.NET operates.

My question is: Where can I find documentation to guide me in deciding where to do what processing?

As a few specific examples (I'm interested in answers to these but I'd rather be pointed at a resource that gives more general answers):

  • What processing should I do in Page_Load?
  • What processing should I do with the Load event?
  • What can I do in Page_Unload?
  • What order do things get done in?
  • When is each event fired?
  • What is the page life-cycle?

edit: this question might also be of use to some people.

like image 522
BCS Avatar asked Jul 27 '09 19:07

BCS


2 Answers

The links posted by various folks are very helpful indeed - the ASP.NET page life cycle really isn't always easy to grok and master!

On nugget of advice - I would recommend preferring the overridden methods vs. the "magically" attached methods, e.g. prefer the

protected override void OnLoad(EventArgs e)

over the

protected void Page_Load(object sender, EventArgs e)

Why? Simple: in the overridden methods, you can specify yourself if and when the base method will be called:

protected override void OnLoad(EventArgs e)
{ 
    base.OnLoad(e);
    // your stuff
}

or:

protected override void OnLoad(EventArgs e)
{ 
    // your stuff
    base.OnLoad(e);
}

or even:

protected override void OnLoad(EventArgs e)
{ 
    // some of your stuff
    base.OnLoad(e);
    // the rest of your stuff
}

or even:

protected override void OnLoad(EventArgs e)
{ 
    // your stuff
    // not call the base.OnLoad at all
}

You don't have that flexibility in the Page_Load() version.

Marc

like image 145
marc_s Avatar answered Nov 04 '22 12:11

marc_s


The first thing you need to learn to be able to understand the the questions you just asked is: PAGE LIFE CYCLE. It is a bitch sometimes, especially the ViewState part.

•What processing should I do in Page_Load?

•What processing should I do with the Load event? = Page_load

•What can I do in Page_Unload? Clean up

•What order do things get done in? PAGE LIFE CYCLE

•When is each event fired? PAGE LIFE CYCLE

•What is the page life-cycle? alt text

Edit: Image source: http://www.eggheadcafe.com/articles/20051227.asp

More info: http://www.codeproject.com/KB/aspnet/PageLifeCycle.aspx

like image 35
Colin Avatar answered Nov 04 '22 11:11

Colin