difference between Page_Init vs OnInit - asp.net

I had an interview a week ago and one of the questions was what the difference between OnInit, Page_Init and PreRender. which one is preferable?

Page_Init is an event handler for the Page.Init event, you typically see it if you add a handler within the class itself.
OnInit is a method that raises the Init event.
The two can be seen as being equivalent if used within a subclass, but there is a difference: only Init is exposed to other types, the OnInit method is protected and is responsible for raising the event, so if you override OnInit and fail to call base.OnInit then the Init event won't be fired. Here's how it looks like:
public class Page {
public event EventHandler Init;
public event EventHandler Load;
protected virtual void OnInit(Object sender, EventArgs e) {
if( this.Init != null ) this.Init(sender, e);
}
protected virtual void OnLoad(Object sender, EventArgs e) {
if( this.Load != null ) this.Load(sender, e);
}
public void ExecutePageLifecylce() {
this.OnInit();
// do some houskeeping here
this.OnLoad();
// further housekeeping
this.Dispose();
}
}
public class MyPage : Page {
public MyPage() {
this.Init += new EventHandler( MyPage_Init );
}
private void MyPage_Init(Object sender, EventArgs e) {
// No additional calls are necessary here
}
protected override void OnLoad(Object sender, EventArgs e) {
// you must make this following call for any .Load event handlers to be called
base.OnLoad(sender, e);
}
}
Generally overriding the OnLoad / OnInit methods is faster (but this is a microptimisation, you're only saving a couple of extra instructions for delegate dispatch) and many "purists" will argue using events unnecessarily is just ugly :)
Another advantage of not using events is avoiding bugs caused by AutoEventWireUp which can cause events to be called twice for each page load, which obviously is not desirable if your event-handlers are not idempotent.

Related

Call parent page function from user control

I have a Default.aspx page and I am using a usercontrol in it. On some condition in usercontrol.cs I have to invoke a function present in Default.aspx.cs page (i.e parent page of user control). Please help and tell me the way to do this task.
You have to cast the Page property to the actual type:
var def = this.Page as _Default;
if(def != null)
{
def.FunctionName();
}
the method must be public:
public partial class _Default : System.Web.UI.Page
{
public void FunctionName()
{
}
}
But note that this is not best-practise since you are hard-linking the UserControl with a Page. Normally one purpose of a UserControl is reusability. Not anymore here. The best way to communicate from a UserControl with it's page is using a custom event which can be handled by the page.
Mastering Page-UserControl Communication - event driven communication
Add an event to the user control:
public event EventHandler SpecialCondition;
Raise this event inside your user control when the condition is met:
private void RaiseSpecialCondition()
{
if (SpecialCondition != null) // If nobody subscribed to the event, it will be null.
SpecialCondition(this, EventArgs.Empty);
}
Then in your page containing the user control, listen for the event:
public partial class _Default : System.Web.UI.Page
{
public void Page_OnLoad(object sender, EventArgs e)
{
this.UserControl1.OnSpecialCondition += HandleSpecialCondition;
}
public void HandleSpecialCondition(object sender, EventArgs e)
{
// Your handler here.
}
}
You can change the EventArgs to something more useful to pass values around, if required.
parent.aspx.cs
public void DisplayMsg(string message)
{
if (message == "" || message == null) message = "Default Message";
Response.Write(message);
}
To Call function of parent Page from user control use the following:
UserControl.ascx.cs
this.Page.GetType().InvokeMember("DisplayMsg", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { "My Message" });
This works fine for me..
Try this
MyAspxClassName aspxobj= new MyUserControlClassName();
aspxobj.YourMethod(param);

Custom Image Button control click handler not firing

I've got a bit of an issue with creating a new control based on ASP.NET's ImageButton control. Everything works as expected, except for the click handler that is being hooked up in the control's OnInit override. Basically, clicking the custom image button just refreshes the page, never hitting the handler.
Now, I know this is something stupid I've done or just not understood, but I can't for the life of me figure this out. All the articles, questions and forum posts I've found on event handling issues for controls is for child controls, rather than ones that inherit from existing control types and have their own predefined handlers.
The following code is what I've written:
public class WebPaymentButton : ImageButton
{
public string DisabledImageUrl { get; set; }
public string TermsAcceptClass { get; set; }
protected override void OnPreRender(EventArgs e)
{
Page.ClientScript.RegisterClientScriptResource(typeof (WebPaymentButton), "PaymentModule.Scripts.WebPaymentButtonScript.js");
}
protected override void OnInit(EventArgs e)
{
CssClass = "WebPaymentButton";
if (!string.IsNullOrWhiteSpace(TermsAcceptClass))
{
Attributes["data-TermsClass"] = TermsAcceptClass;
}
if (!string.IsNullOrWhiteSpace(DisabledImageUrl))
{
Attributes["data-DisabledImageUrl"] = ResolveUrl(DisabledImageUrl);
}
Click += WebPaymentButton_Click;
base.OnInit(e);
}
private void WebPaymentButton_Click(object sender, ImageClickEventArgs e)
{
HttpContext.Current.Response.Redirect("http://dummy_payment_page_in_place_of_code", true);
}
}
I've tried hooking the handler up in the OnLoad and also switching it to run after the base.OnInit/OnLoad calls. Nothing has solved the handler issue. Can anyone point me in the right direction?
In case it helps, here is the markup for the button on the page:
<pm:WebPaymentButton runat="server" ImageUrl="~/pay-now.png" DisabledImageUrl="~/not-pay-now.png" TermsAcceptClass="TermsCheckbox" ID="MainPayButton" />
Have you tried overriding the OnClick event handler instead of hooking up to a new event handler?
Remove the Click += WebPaymentButton_Click line from OnInit and remove the WebPaymentButton_Click function, then add the following code to your class instead:
protected override void OnClick(ImageClickEventArgs e)
{
base.OnClick(e);
HttpContext.Current.Response.Redirect("http://dummy_payment_page_in_place_of_code", true);
}

can httphandler fire an event?

I want to check Session in some pages. To do this I am adding the page names which I want to check inside web.config as a appsetting key.
I want to use httpHandler with firing an event after it finds the session is empty or something else.
If I create httpHandler as a dll(another project) and add to a web site, can handler fire an event and web site capture it inside a web page?
What you can do is this:
Your HttpHandler puts a value in the HttpContext.Current.Items collection telling if there was Session or not. Something like
HttpContext.Current.Items.Add("SessionWasThere") = true;
You create a BasePage that checks that value in the Page_Load event and raises a new event telling so:
public abstract class BasePage : Page {
public event EventHandler NoSession;
protected override void OnLoad(EventArgs e){
var sessionWasThere = (bool)HttpContext.Current.Items.Add("SessionWasThere");
if(!sessionWasThere && NoSession != null)
NoSession(this, EventArgs.Empty);
}
}
In your page, you suscribe to that event:
public class MyPage : BasePage{
protected override void OnInit(){
NoSession += Page_NoSession;
}
private void Page_NoSession(object sender, EventArgs e) {
//...
}
}

Page.InitComplete handler is not executed

I've run into a weird problem while developing a control. I've registered a handler for Page.InitComplete event from the control, but the handler is not executed. I need the handler to be executed exactly on InitComplete event, because I depend on complex application architecture.
My code looks like this (This code is placed inside my control class):
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Page.InitComplete += (sender, args) => OnInitComplete(args);
}
However OnInitComplete is never entered.
If it is somehow possible I would like to find the way to register my handler to Page.InitComplete event without using my own events & weird hacks.
Apart from that I'm curious about the reason of this behaviour.
I'm sorry - my fault. The problem was in custom PageBase class :
protected override void OnInitComplete(EventArgs e)
{
if (!String.IsNullOrEmpty(FormAction) && FormActionInitComplete != null)
{
FormActionInitComplete(FormActionSender, FormAction, FormActionValue);
}
}
The Page.OnInitComplete method is implemented in the following way :
protected virtual void OnInitComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventInitComplete];
if (handler != null) {
handler(this, e);
}
}
and in the overriden method of the PageBase there was no call of the base.OnInitComplete method - that is why the event was not raised.

How do I avoid calling my initialization method repeatedly in ASP.NET?

protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) { // sadly, **never** in here }
MyInit() // Slow initialization method, that I only wan't to call one time.
}
So, if I can't tuck my MyInit() in the if, can I solve my performance/strucktur problem with use of OnNeedDataSource()?
Not really sure if this is what you mean, but to initialise something once from Page_Load, you could use a static class with a static bool to determine if it's been initialized. Given it's on Page_Load, you'll also need to guard against multiple threads - so use a double checked lock to make it threadsafe and guard against a race condition.
public static class InitMe
{
private static bool isInitialized = false;
private static object theLock = new Object();
public static void MyInit()
{
if(!isInitialized)
{
lock(theLock);
{
if(!isInitialized) // double checked lock for thread safety
{
// Perform initialization
isInitialized = true;
}
}
}
}
}
and in your Page_Load, call it via InitMe.MyInit()
Hope that helps.
Try this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack) { MyInit(); }
}
I assume you are in a page or user control...
HTH.

Resources