Page unload event in asp.net - asp.net

Is it possible to call a write a Page_Unload event in code behind similar to Page_Load event? I wanted to call a method on Page Unload. How do I achieve that?

With AutoEventWireup which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
For details see the MSDN article.

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
// your code
}
But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

There is an event Page.Unload. At that moment page is already rendered in HTML and HTML can't be modified. Still, all page objects are available.

Related

Using Page_Load and Page_PreRender in ASP.Net

I see some people are using Page_Load and Page_PreRender in same aspx page. Can I exactly know why do we need to invoke both the methods in same asp.net page?
Please see the code below,
protected void Page_Load(object sender, EventArgs e)
{
try
{
dprPager.ButtonClickPager += new EventHandler(dprPager_ButtonClickPager);
if (!Page.IsPostBack)
{
InitPager();
}
}
catch (Exception ex)
{
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
erMsg.Visible = !string.IsNullOrEmpty(lblError.Text);
}
The major difference between Page_Load and Page_PreRender is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load() methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender is your last chance to tweak the page before it turns into HTML stream.
It depends on your requirements.
Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.
Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.
Reference: Control Execution Lifecycle MSDN
Try to read about
ASP.NET Page Life Cycle Overview ASP.NET
Control Execution Lifecycle
Regards
Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load
is the more typical event to work with.
Well a big requirement to implement PreRender as opposed to Load is the need to work with the controls on the page. On Page_Load, the controls are not rendered, and therefore cannot be referenced.
Processing the ASP.NET web-form takes place in stages. At each state various events are raised. If you are interested to plug your code into the processing flow (on server side) then you have to handle appropriate page event.
The main point of the differences as pointed out #BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing.
Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.

Events are not working if UserControl.ascx are loaded through LoadControl(ctr)

I find this as a funny little problem. I think the reason lies behind the life-cycle of page-object/events-generation, but the question is how I come around the problem?
In Default.aspx there exist some funny controls but also a
<asp:PlaceHolder runat="server" id="phUserContent"></asp:PlaceHolder>
This placeholder is empty until runtime. Code behind are, in some circumstances, loading UserControls into it. Like this
Control ctr = LoadControl("~/UserControl/Note.ascx");
phUserContent.Controls.Add(ctr);
This Note.ascx contains some interesting controls and finally a LinkButton that fires an event. The LinkButton-code are very easy and gramatically correct,
<asp:LinkButton runat="server" ID="lbUpdate" OnClick="lbUpdate_Click" Text="Update"></asp:LinkButton>
In the Code behind for the ascx I have the code for the event,
protected void lbUpdate_Click(object sender, EventArgs e)
{ ... }
As I wroted, the postback occurs, the page are regenerated as I would suspect - but without the lbUpdate_Click event to be executed. A break-point is of course tried.
I'm looking for two possible scenarios. One is that I missed something really easy (you know, like wroted in wrong code behind file) or that I missed an important part of the Page Generation Cycle.
I'm mostly into the second, like this (i just think here..)
1. Page (ascx) got it's changes
2. Submit was clicked
3. Ascx was re-generated
4. Events was cleared but was exist and doesnt cast error.
5. After reload, initial content was reloaded
The effect would be that the compiler can't see the breakpoint and the values was never saved due to a "execution of an empty event". But this is just a amateours guess, please advice me.
[UPDATE AS PER ANSWER]
This is how I was solved it, based on the acepted answer below.
List<Control> ctr;
public User()
{
ctr = new List<Control>();
}
protected void Page_PreInit(object sender, EventArgs e)
{
ctr.Add(LoadControl("~/UserControl/Note.ascx"));
}
protected void Page_Load(object sender, EventArgs e)
{
ctr.ForEach(d => phUserContent.Controls.Add(d));
}
Shortly..
1. The class got a list of Controls
2. In Page_PreInit (before creation) add UC (u can have X of them here)
3. In Page_Load (where all ctr are created) add each UC to the PH.
Which also make the events in the UC also working, no magic and no dumb complications :-)
It's a lifecycle issue.
Remember, every page request creates a new Page object, and new instances of all the controls on it. If you are dynamically creating a control, then it has to be done in the exact same manner on every postback. If you want the new control to fire an event, then it has to have the same id as the old one, and have the event hooked up to it before control events are processed in the lifecycle.
If you're creating the control dynamically at a point in the page lifecycle that occurs after ViewState is handled, then you'll have to manage your own state as well. In other words, if you're not dynamically creating the control during the PreInit phase, then you'll have to manually deal with restoring state.

What calls Page_Load and how does it do it?

Page_Load isn't a virtual method. What calls this method and how does it do it? Is it reflection or some other technique? Also how many events are handled this way?
Also is it preferable to handle things in an overloaded OnLoad or Page_Load? How are they different?
ASP.NET has a feature called "AutoEventWireup" - this feature allows you to create methods that have the EventHandler signature with names like Page_Load and the runtime will wire up the event from the parent page to the method in your class. Basically the runtime does this on your behalf:
this.Load += this.Page_Load;
Now it is better to disable AutoEventWireup and either create these event handlers yourself in the pages OnInit method or simply override the parent page's OnLoad method.
Edit (in response to the OP's comment below): This process doesn't cover button clicks and such but the process is similar.
In order for a method like MyButton_Click to work without you explicitly creating an event handler you would have to set the OnClick attribute on the control in the aspx file like this:
<asp:button
id="MyButton"
onClick="MyButton_Click"
runat="server" />
This would prompt ASP.NET to create the button click delegate for you and attach it to the button's Click event.
The order in which the virtual methods (OnLoad) and event handlers (Page_Load) are called is defined by the so called page lifecycle. This is just the way how the ASP.NET runtime processes an incoming request (e.g. with the Init, Load, Render stages).
You can use either OnLoad or Page_Load but you have to be aware of what happens:
inside OnLoad you must call base.OnLoad
inside base.OnLoad the Load event will be raised
Page_Load is a handler for the Load event (which is automatically wired-up) and will therefore be invoked as a result of the Load event that's being raised.
If you do not call base.OnLoad in your OnLoad override, then the Load event will not be raised.
Update: you can use an empty page with the following code-behind to see what happens:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
base.Load += new EventHandler(My_Page_Load);
}
void My_Page_Load(object sender, EventArgs e)
{
Response.Write("My_Page_Load<br/>");
}
protected override void OnLoad(EventArgs e)
{
Response.Write("Start of OnLoad<br/>");
base.OnLoad(e);
Response.Write("End of OnLoad<br/>");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page_Load<br/>");
}
Try commenting the base.OnLoad(e) call and see again.
The OnLoad method somewhere up the Page hierarchy calls the events assigned to Load (via +=).
The naming Page_Load is just a convention. In AutoEventWireUp mode (i.e. no event handler explicitly declared) this convention is used to find event handlers by their names.
If you have .Net1 available, you can see how the designer adds code to the page's OnInit() to add all components of the page and set
this.Load += new System.EventHandler(this.Page_Load);
.Net2 still does that, but in a separate file which is hidden somewhere under the Windows\Microsoft.Net\Framework\v*\Temporary ASP.Net Files.
I find this chart on ASP.Net Page Life Cycle very useful.
Take a look at the ASP.NET page lifecycle, there is a section for lifecycle events where it describes load.
Load
The Page calls the OnLoad event
method on the Page, then recursively
does the same for each child control,
which does the same for each of its
child controls until the page and all
controls are loaded. Use the OnLoad
event method to set properties in
controls and establish database
connections.
Further Quote:
Note that when creating an event
handler using the Page_event syntax,
the base implementation is implicitly
called and therefore you do not need
to call it in your method. For
example, the base page class's OnLoad
method is always called, whether you
create a Page_Load method or not.
However, if you override the page
OnLoad method with the override
keyword (Overrides in Visual Basic),
you must explicitly call the base
method. For example, if you override
the OnLoad method on the page, you
must call base.Load (MyBase.Load in
Visual Basic) in order for the base
implementation to be run.
In the page directive it says: Autoeventwireup="true"
Thats what happens, its automatically wired up to the Load event... (and some other events like PreInit, Init, Unload etc.)

ASP.NET Page_Init Fired Twice!

I have AutoEventWireup="true" and in my code behind
protected void Page_Init(object sender, EventArgs e)
{
}
When I'm debugging, the Page_Init method is getting fired twice!
Whats going on?
Let's make sure we cover the basics here:
Do you have any controls on your page that have server events? If so, remember that every postback re-creates the entire page. So, to handle an event means running all of the code required put the page together, including your Init and Load events.
Always two there are, no more no less. A request and a response.
You probably have some sort of redirect or ajax postback that is firing.
Do you have any code anywhere that looks something like this?
this.Init += Page_Init;
If so you are accidentally wiring the event twice. Either delete the manual event wiring or set AutoEventWireup to false.

Refresh the page after a postback action in asp.net

I have command button added in my asp.net grids. After performing an action using that button, we refresh the grid to reflect the new data. (basically this action duplicates the grid row).
Now when user refresh the page using F5, an alert message is displayed (to resend the information to server) if we select "retry", the action is repeated automatically.
I know this is a common problem in asp.net, how can we best handle this?
Search for GET after POST - http://en.wikipedia.org/wiki/Post/Redirect/Get - basically, redirect to the current page after you're finished processing your event.
Something like:
Response.Redirect(Request.RawUrl)
If you think you don't need postback paradigm, you might want to look at ASP.NET MVC.
The problem is that asp.net buttons perform form posts when you push a button. If you replace the button with a link your problem should go away. You can also use a button that performs a javascript function that sets the document.location to the address of your page.
If I well understood, you simply have to check if you are in a post-back situation before populating your grid.
Assuming you do that on Page_Load, simply surround the operation with post-back test like this:
private void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
// populate grid
}
}
You need to call response.Redirect(Request.Url.ToString());
or you can wrap the grid with updatepanel and after every command bind the datasource to grid
Inside your <asp:Repeater> tag put this:
EnableViewState="false"
This will cause your control to refresh every time the page loads, no matter if it's a postback or not.
for example:
if you click on 'button' system will catch the event 'button_click'.
if you refresh the page, system will re execute again the same event.
to don t have this problem, in your event insert :
on your event
private void button_click(object sender, System.EventArgs e)
{
button.Enabled =false;
button.Enabled =true;
}
is what you meant?

Resources