In an ASP.NET web form, how to determine what causes a Page_Load()

1.1k views Asked by At

I want to implement a finite state machine (FSM) inside a typical ASP.NET web form. I would like the FSM "engine" to be automatically invoked each time a Page_Load() event happens - which is easy enough - but I also want the engine to receive information about which event caused the Page_Load() to occur. The difficulty is that in an ASP.NET web form, a user-controlled event, such as a button click, can cause the page to reload, but the event handler for the button click itself does not get invoked until after the Page_Load() event fires. As far as I can tell, the Page_Load() handler itself does not contain any information about what user event caused the page to reload. I would prefer not to have to explicitly invoke the FSM engine from within each event-handler method. Is there any way to accomplish this? -- to have Page_Load(), or some other stage in the page life-cycle, "know" what particular user action caused the page to reload?

1

There are 1 answers

2
CodingYoshi On

ASP.NET Web forms will store it in a parameter in the Request object. You can get it like this:

// Find the control name
string nameOfControlWhichCausedPostback = page.Request.Params.Get("__EVENTTARGET");

Then find the control with that name:

if (!String.IsNullOrWhitespace(nameOfControlWhichCausedPostback ))
{
    var ctrl = page.FindControl(nameOfControlWhichCausedPostback );
}