Tuesday, June 2, 2015

Finding which event fired(button clicked) in Page_Load or Page_Init/Page_PreInit

I was working on an app and I wanted to turn off Event Validations when a certain action was performed to Render the HTML. Keeping them on won't let me render my UserControl to an HTML file. So I wanted to capture the Event right in Page_PreInit so that I can disable Event Validation of Page. Note that this can only be done either programmatically before Page is Initialized, or as a Page directive in aspx file.

Request.Form["__EVENTTARGET"] is the variable that will capture the information for the button clicked.

One additional aspect to note is to have UseSubmitBehavior="false" for the Button Web Control to generate the value for "__EVENTTARGET".

So in your html:

<asp:Button runat="server" ID="btnDownload" UseSubmitBehavior="false" ClientIDMode="Static" Text="Download" style="display:none;" OnClick="btnDownload_Click" />

In code behind, this is what you would have:


protected void Page_PreInit(object sender, EventArgs e) 
 { 
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("btnDownload"))
Page.EnableEventValidation = false;//(NO INTELLISENSE!)disable event validation when the button is clicked for downloading file
}