There may be scenarios where we require to know which control has triggered the postback event both at client-side and server-side.
For all the controls except button and Imagebutton
Below are two hidden fields added by Asp.net.
<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” /> “__EVENTTARGET” value is set to the control id who has triggered the postback. This happens for all the controls except button and Imagebutton.
At client side, on body onbeforeunload event, check the value of “__EVENTTARGET” , this will return the control ID of the control which has triggered the postback.
|
document.getElementById(‘__EVENTTARGET’).value; At server side, on Page_load check the control which has caused the postback. string controlName = Request.Params.Get(“__EVENTTARGET”); For Buttons and Imagebuttons For Buttons and ImageButton, the “__EVENTTARGET” is set to empty string. At server side check the “__EVENTTARGET”, If its empty and check the control type to know which button has triggered the postback foreach (string controlID in Request.Form)
{
Control objControl = Page.FindControl(controlID);
if (objControl is Button)
{
control = objControl;
break;
}
}
Explanation: In ASP.net, all the controls (except buttons and imagebuttons) uses javascript function __doPostBack to trigger postback. |
<script type="text/javascript"> //<![CDATA[ var theForm = document.forms['Form1']; if (!theForm) { theForm = document.Form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script>
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTTARGET will always be empty.
When the user clicks on the “Submit” button, the content of the form is sent to the server. The form’s action attribute defines the name of the file to send the content to.
The form data (key-value pair) sent to the server has the button control id that has caused the triggered postback.