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

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.

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

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?
Edit: Image source: http://www.eggheadcafe.com/articles/20051227.asp
More info: http://www.codeproject.com/KB/aspnet/PageLifeCycle.aspx

Here are some good links to get you started. Understanding how the ASP.NET life-cycle fits together is critical to understanding how your code will interact with it.
ASP.NET Page Life Cycle Overview:
When an ASP.NET page runs, the page
goes through a life cycle in which it
performs a series of processing steps.
These include initialization,
instantiating controls, restoring and
maintaining state, running event
handler code, and rendering. It is
important for you to understand the
page life cycle so that you can write
code at the appropriate life-cycle
stage for the effect you intend.
Additionally, if you develop custom
controls, you must be familiar with
the page life cycle in order to
correctly initialize controls,
populate control properties with
view-state data, and run any control
behavior code. (The life cycle of a
control is based on the page life
cycle, but the page raises more events
for a control than are available for
an ASP.NET page alone.)
The ASP.NET Page Life Cycle:
When a page request is sent to the Web
server, whether through a submission
or location change, the page is run
through a series of events during its
creation and disposal. When we try to
build ASP.NET pages and this execution
cycle is not taken into account, we
can cause a lot of headaches for
ourselves. However, when used and
manipulated correctly, a page's
execution cycle can be an effective
and powerful tool. Many developers are
realizing that understanding what
happens and when it happens is crucial
to effectively writing ASP.NET pages
or user controls. So let's examine in
detail the ten events of an ASP.NET
page, from creation to disposal. We
will also see how to tap into these
events to implant our own custom code.

ASP.net page lifecycle

I would definitely recommend you reading this:
http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp
If you're new to asp.net you'll have some trouble getting all of that, but really, I have yet to find such a detailed document on the topic comming from ms documentation or any ms employee blog.
I did it the hard way and followed every path I could using disassembled code but that guy really took the time to write it.

Basically try and do it in Page_Load and if that doesn't work, try it in either Page_Init or Page_Render. Normally one of them works :) That's the scientific approach.

Related

Prevent rendering of user control

in our asp.net webforms application, we dynamically load usercontrols into placeholders. In order to retain changes across post-backs, our page-life-cycle is a little more complex than usual. We ALWAYS restore the previous control structure in pageInit in order to successfully load our viewstate. Only then do we clear the placeholder and load a new control into it.
This unfortunately means an entire life-cycle both for the old AND the new usercontrol, including server-side-processing of the old module's entire .ascx markup-file.
Now my question: Is there any possibility to minimize server-side processing of the old module, as it never gets sent back to the client (i.e. it's server-side rendering is completely unnecessary). What I'd ideally want to achieve is a sort of "light-weight" loading of a usercontrol, when it's only purpose is restoring vewstate information without it ever reaching the client.
The goal of the exercise is performance optimization.
Any hints, ideas or suggestions appreciated!
I have resolved code running in webcontrol lifecycle events of dynamically added controls by simply checking if the control was visible (http://msdn.microsoft.com/en-us/library/system.web.ui.control.visible.aspx)-
protected void Page_Load(object sender, EventArgs e)
{
if (this.Visible)
{
//Your code here
}
}
If you have any methods that aren't triggered by a page lifecycle event, and have to be triggered by a user action, such as-
protected void Button1_Click(object sender, EventArgs e)
{
//Do something
}
This can safely be left as is, the method code will not be run until the control is added to the page and the action is triggered.
Although the visibility check doesn't feel especially elegant, it's probably the best way to deal with auto wired events on dynamically loaded controls.

Are there any conditions where a MasterPage Page_PreInit() is executed?

Based on a configuration setting I'd like to direct users to a "This site is currently offline" page. The master page seems like the common place to do that. I originally used this code:
MyConfig config = new MyConfig();
protected void Page_PreInit(object sender, EventArgs e)
{
if (config.RefuseRequests)
Response.Redirect("Offline.aspx");
}
A break point here is never hit.
After some digging I came across http://msdn.microsoft.com/en-us/library/dct97kc3.aspx which seems to say a master Page_PreInit is never called. Am I reading that right?
The above code doesn't show an error in visual studio and it seems like a useful step in the load flow. Are there any conditions where a master page Page_PreInit would be executed?
While the information out there isn't as clearly stated as I'd like the practical answer does appear to be "no, a master Page_PreInit() will never be hit."

Page_Load Vs Page_InitComplete in ASP.Net

I've seen programmers writting in Page_Load like
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
}
}
So that the codes will be worked only once.
If so, why don't we put that code in Page_InitComplete? Since Page_InitComplete is done only once.
What are the pros and cons by doing so?
I don't see any advantage to what you're suggesting but I can see problems with it. For one thing, server controls do not yet have their data loaded during InitComplete. For another thing, code in this event executes regardless if whether or not it's a postback.
Use the Load event. That's what it's for. It only executes once per request. If you want to restrict code to only run on postbacks, or only run during non-postback requests, test IsPostBack.
Perhaps you can answer your own question reading through the ASP.NET Page Life Cycle Overview. The InitComplete is triggered only once but on each post back just like the Load event.

Performance-impact of empty Page_Load() methods

When adding a new page or user control to an ASP.NET webforms application, the code-behind class contains an empty Page_Load() event handler:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have an existing web app, where many pages and controls still contain these empty event handlers (they are not used).
Question: Is there any performance impact due to these empty event handlers and should they therefore be removed from all pages and controls?
Please note: I'm not mainly (or not only) concerned about any runtime-overhead, due to the empty event handler being called. I also wonder about any overhead while the page (markup) is JIT-compiled (because the event handlers have to be wired up to the events - probably using some reflection code).
Update: there was no real answer so far, so I can't accept any of them.
AutoEventWireup is not done at the compile time. When it set to true, the runtime has to look for each of the page event handlers using Delegate.CreateDelegate method for this. Here is a great article which describes this behaviour: Inside AutoEventWireup.
There is a similar question here: What is the performance cost of autoeventwireup?
While the stack frame must be adjusted to enter and leave your method (and doing nothing) as opposed to simply calling the base implementation (in this case System.Web.UI.Page
), the performance impact is incredibly small and most likely unmeasurable so you should be fine.
I'm fairly certain Page_Load occurs whether it's there or not. Much like PreRender occurs, or Page_Init.
Removing it will do nothing for performance.

Page_Load or Page_Init

Let's take a really simple example on using jQuery to ajaxify our page...
$.load("getOrders.aspx", {limit: 25}, function(data) {
// info as JSON is available in the data variable
});
and in the ASP.NET (HTML part) page (only one line)
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="getOrders.aspx.cs" Inherits="getOrders" %>
and in the ASP.NET (Code Behind) page
public partial class getOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string lmt = Request["limit"];
List<Orders> ords = dll.GetOrders(limit);
WriteOutput( Newtonsoft.Json.JsonConvert.SerializeObject(ords) );
}
private void WriteOutput(string s)
{
Response.Clear();
Response.Write(s);
Response.Flush();
Response.End();
}
}
my question is
Should it be
protected void Page_Load(object sender, EventArgs e)
or
protected void Page_Init(object sender, EventArgs e)
So we can save some milliseconds as we don't actually need to process the events for the page, or will Page_Init lack of some sorting of a method by the time it is called?
P.S. Currently works fine in both methods, but I just want to understand the ins and outs of choosing one method over the other
Basic page life cycle will answer your question Full article : http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle.aspx
check same question answer : Page.Request behaviour
Either one would work, because you're essentially throwing out the page lifecycle by calling response.Clear() and response.End(). Technically you could even go as far as putting that code in prerender and it would work. By accessing the Response object you're basically going over the head of the page and cutting it off mid-stride so that you can perform a much simpler task.
I assume you simply do not want the page lifecycle at all and simply want to return JSON from this page? If so, I highly recommend implementing it as a Generic Handler (ashx). In this case you'd simply use context.Request["limit"] and context.Response.Write in your Process method. The benefit of doing this is that you don't have all the overheads of .NET preparing the page class and starting the page lifecycle, and are instead using a file intended for the task you're doing.
It is nice to understand the page lifecycle, as shown in other answers, but realistically you're not using it at all and you'd be better off moving away from the page class entirely.
Page life-cycle only has meanings in context of page elements (controls), so i don't see any differences in your case, since you don't have any other child controls in your page - this is totally irrelevant.
But here is the real question: if you don't have any rendering of html in your page (only data serialization), why you have choose to work with regular .aspx page?
Web service is ideal candidate for this scenario. And you'll be surprised how much performance improvement you'll gain in the end.
You can very well use the Page Init method. But if you have controls in your page and want to access any property of those controls then better to use the Page load event, but in your case you don't need to use page load event.
You can go through the Asp.Net Page Life cycle here to better understand which event to use.

Resources