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.
Related
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.
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.
When an asynchronous postback happened inside update panel, another postback happens also for MasterPage not only update panel embedded page .
I want to prevent this MasterPage postback .
is this possible ?
think like i have a MasterPage
and another page which is test.aspx which is content page of MasterPage
i have update panel at test.aspx
when asynchronous postback happens at this test.aspx update panel it also loads MasterPage Page_Load
i want to prevent this (it should not also load MasterPage Page_Load)
Thank you
ASP.NET's UpdatePanel (as well as any normal asp.net page)'s postback does postback the master page as well.
Normally, to properly deal with postbacks, programmers check for it and program accordingly :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dataBindAndSetUpControls();
}
}
So, my answer here is that I don't know if it is possible (and if it is, it certainly isn't easy), and that your request is not a normal thing to do, and programmers handle PostBacks via the blurb above.
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.
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?