asp.net prevent events from being raised - asp.net

I have a control (.ascx) that sits on a page (.aspx). Within that control there's a asp.net update panel that encompasses everything for that control. When the control does a post back it automatically raises all the events from the control plus all the events from the page it sits on. This is causing significant performance problems.
Is there any way to stop the events from being raised that reside on the page that the control is sitting on?
Thanks

Check the ScriptManager.IsInAsyncPostBack Property.
Here is the sample code:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// get a reference to ScriptManager and check if we are in a partial postback
if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
{
// partial (asynchronous) postback occured
// insert Ajax custom logic here
}
else
{
// regular full page postback occured
// custom logic accordingly
}
}
}

Related

asp.net dynamic user control button click issue

I made researching about this subject I could not find proper answer.
In my default.aspx page, I have a treeview. Codes are in default.aspx like below:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Control ucont;
if (TreeView1.SelectedNode.Value == "Yeni Dönem")
{
ucont = LoadControl("usercontrols/yenidonem.ascx");
PlaceHolder1.Controls.Add(ucont);
}
else
{
ucont = LoadControl("usercontrols/tabloktar.ascx");
PlaceHolder1.Controls.Add(ucont);
}
}
I load user controls dnynmicaly. User controls are have button control. I can not fire user control's button click when I load it dynamcally. How can I solve this ?
Thanks.
First of all, I would not recommend adding control dynamically later than in Page_Load event. Other things to remember is that You should add it on each page load and assign unique ID value the control that does not change between postbacks.
In this case, the easiest way would be to always add both controls to the page and show appropriate one using Visibility property.
If that's not suitable for You, try to move the code from TreeView1_SelectedNodeChanged to the Page_Load event and load appropriate control on each postback until it should be changed to another one.
I haven't tested this, so if You have any issues when using thise answer, let me know in the comments and I'll try to help.

Why Master Page does not have OnInitComplete event?

Why Master pages is not required to confirm the initialization completion ?
Although, Master Page can have controls and need initialization and like in content page, confirmation comes in Init-Complete event.
InitComplete is not fired when the child controls of a control finish initialization, but when all the controls on the page are done.
The MasterPage being a control itself, loaded in the page, cannot detect by itself when all the other controls have completed initialization.
If any control, including the master page needs to know when the page initialization is over, it could subscribe to the InitComplete event of the Page.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.InitComplete += Page_InitComplete;
}
void Page_InitComplete(object sender, EventArgs e)
{
//initialization complete
//take necessary action
}

ASP.NET Login Controls, page postback and rendering on logout

I'm a bit puzzled by the behavior of the default ASP.NET Authentication controls, by its lifecycle to be precise.
In my MasterPage, I added a LoginView Control which displays the nice [Login] or [Logout] links. When I am logged in and click on [logout], I set up the control to perform a redirection to the homepage of the application.
Internally, when a click on "logout" happens, a postback is triggered. The following steps happen (among others of course):
The page that fired the postback is reinitialized
The page that fired the postback is reloaded
The LoggingOut event is fired
The LoggedOut event is fired
The page that fired the postback is PreRendered
The redirection happens
The target page is loaded (LoggedOut.aspx in my case)
On most of the pages, this works fine. But some pages expect some data to be initialized for their rendering to happens correctly. When this loggout postback occurs, the data isn't correctly initialized, but the page is still PreRendered which leads to some... "unexpected behavior" >_<
My question is thus twofold:
Why does this rendering step happens since the page won't be displayed at all?
Is there a way to prevent the rendering to happen?
Thanks a lot.
Tim
PS: here's a small VS2010 sample project showing you the call sequence & page lifecycle if you want to try it out for yourself http://dl.dropbox.com/u/11764136/LoginTest.7z
There is a way to prevent the actual rendering of the page.
Stop processing the current request when you redirect the page. This can be done by giving a true parameter to the Response.Redirect method:
Response.Redirect("http://somewhere", true);
You can also do this manually by calling Response.Close();
Are you using if(!isPostBack) test to control what should be rendered/re-initialized and what shouldn't?
Venemo's answer gave me an idea that seems to be working.
Instead of relying on the LoginStatus component to perform the redirection, I registered the MasterPage hosting the LoginStatus components to the LoginStatus.LoggedOut event and fire the redirection "per hand" before the PreRender step can be called.
protected void Page_Load(object sender, EventArgs e)
{
MasterLoginStatus.LoggedOut += new EventHandler(OnUserLoggedOut);
}
private void OnUserLoggedOut(object sender, EventArgs e)
{
Response.Redirect("~/LoggedOut.aspx", true);
}
I was concerned the LoginStatus component might remain dirty by doing this but sofar I haven't found any issue with it e.g. "works until proven otherwise".
Remains the question of "why the component behaves like this" but I guess it was a design decision that will remain unanswered.
Edit: this works fine until you get the same problem for the "login" action. Haven't found a way around this one yet.
I've got a serious problem with a DevExpress control (The report DocumentMap) which sometimes requests the whole report, bypassing the caching mechanism, when the end-user clicks on the logout link on the LoginStatus control. I've tried a lot of approaches to stop dead the "logout" postback so that the report won't get generated (some reports took 5 minutes to render, so the logout action sometimes took that long). I think this is similar to your problem: you don't want to do any heavy processing if the user is logging out. So I've tried a different approach: why didn't I recognize that the postback is indeed a logging out postback? All my pages inherit from a base page, so I've set this code in the base page:
public bool IsLoggingOut { get; private set; }
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
var eventTarget = Request.Params.Get("__EVENTTARGET");
IsLoggingOut = eventTarget != null && eventTarget.Contains("HeadLoginView$HeadLoginStatus");
}
Now all I need to do in my page is to surround any heavy processing with a test of !IsLoggingOut... You could even do you redirect to the LoggedOut page without having to handle any events, just like this:
protected override void OnLoad(EventArgs e)
{
if (IsLoggingOut)
Response.Redirect("~/LoggedOut.aspx", true);
}
Even if you prefer to use the event handler to do that redirect, being able to know that the postback is indeed due to a logout click is a nice thing!
In my case, I was having this problem with the LoginStatus control. I can't see why it is a useful design to post back and Render the page when the user has clicked "logout". Through some tests, I found that I had to let the page go through its entire lifecycle, so Reponse.End() and Response.Transfer() did not work.
My solution was to add event handlers for the LoginStatus LoggedOut event, and then override the Render() method in the master page to do nothing if the user has logged out. I actually had the LoginStatus nested inside a user control that was then in the master page, so I had to bubble the event.
In my user control containing the LoginStatus control, I added an event handler for the LoggedOut event. In the UserStatus.aspx file:
<asp:LoginStatus runat="server" ID="loginStatusDefault" OnLoggedOut="loginStatusDefault_LoggedOut" ... />
Then in the code-behind:
public event EventHandler LoggedOut;
protected void loginStatusDefault_LoggedOut(object sender, EventArgs e)
{
if (this.LoggedOut != null)
this.LoggedOut(sender, e);
}
Now in the master page default.master, I have already included the UserStatus control:
<c:userstatus ID="ctlUserStatus" runat="server" />
and in the code-behind:
protected void Page_Init(object sender, EventArgs e)
{
ctlUserStatus.LoggedOut += ctlUserStatus_LoggedOut;
...
}
bool IsLoggedOut { get; set; }
void ctlUserStatus_LoggedOut(object sender, EventArgs e)
{
IsLoggedOut = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (!IsLoggedOut)
base.Render(writer);
}
For me, the page rendering is what was bombing out when the user clicked "logout", so this took care of the problem for all pages.
What I did was have the logout link or onloggingout control just redirect to another page, "Logout.aspx" which then handles the log out code. Works great actually.
protected void LoginStatus1_LoggingOut(object sender, EventArgs e)
{
Response.Redirect("~/Logout.aspx");
}

Dynamiclly added control i.e panel contains buttons event no firing

protected void container1ActiveTabChanged(object sender, EventArgs e)
{
if (container1.ActiveTabIndex == 0)
{
if (container1.Tabs[0].Controls.Count == 0)
{
container1.Tabs[0].Controls.Add(gdvEmployee);
}
}
if (container1.ActiveTabIndex == 1)
{
pnlEmployeeID.Visible = true;
pnlEmployeeInformation.Visible = false;
}
if (container1.ActiveTabIndex == 2)
{
pnlEmployeeInformation.Visible = true;
if (container1.Tabs[2].Controls.Count == 0)
{
container1.Tabs[2].Controls.Add(pnlEmployeeInformation);
}
}
this event not firing
protected void btnInsertClick(object sender, EventArgs e)
Why is my event not firing
I'm assuming you are adding the control which fires the event dynamically.
The most common cause of this issue is that the control that fires the event is dynamically added on every postback.
This causes the previous instance of the control to be replaced.
This in turn causes the event to get "lost" as the control which triggered the event is now gone.
When an event is triggered it is "queued" and will execute after a page has been reloaded.
Once the page has been reloaded the event is executed.
If you replace/recreate the control on every postback i.e in the page load event, you are destroying the trigger of the event and in turn destroy the event.
Ensure you are only adding the control ones when the page is created the very first time but do not re-add the control when Page.IsPostback is true.
Using dynamic controls requires some knowledge of the page life cycle to prevent confusion and endless hours of debugging.
If you are not adding a control dynamically, please feel free to elaborate where your event is triggered from and how the trigger is implemented. I'm sure we will be able to help you to pinpoint and solve the problem with any additional information you have.
Additional Reading
This explains all about page life cycles and view state.
Understanding ASP.NET View State
I'm just guessing, but you probably add the dynamic controls in the Page_Load stage. This is quite a common mistake. Try doing the same at the Init stage:
protected void Page_Init(object sender, EventArgs e)
{
// Your controls should generate here
}

disabling ASP.NEt Validtor such that its disabled on postback

I am trying to disable ASP.Net Validator such that its disabled on postback.
I am disabling the validator on client side using
$('.c_MyValidator').each(function() {
ValidatorEnable(document.getElementById($(this).attr('id')), false);
});
but when the page postbacks, my page is still invalid.
I am in UserControl (.ascx) so no override for Validate() for me.
How can I disable the validator such that its enabled=false when the page postbacks.
Any ideas?
There is an example for your scenario here. Basically in server side code, set the enabled property of the validator to the checked property of the checkbox (as well as call the client ValidatorEnable). Use the Page_Load event of your user control because there is no Validate method.
public partial class CheckboxAndValidator : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
validator.Enabled = cbControlValidation.Checked;
}
}
What you can't do is validate your page in the Page_Load event. This is too early and needs to be done later in the page life-cycle once the user control has done it's bit.

Resources