Showing posts with label control. Show all posts
Showing posts with label control. Show all posts

Wednesday, May 12, 2010

Which control triggered the postback

In general, all ASP.NET controls with having autopostback property enabled, emit following HTML.
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

whenever any control triggers the postback, its id is set in hidden variable __EVENTTARGET and any other related information is set in __EVENTARGUMENT. ASP.NET uses its inbuilt __doPostBack script function to pass these values on form submit. You might have guessed it now, that to know which control caused the postback get it from Request.Item("__EVENTTARGET")

It is worth to mention here that the above mentioned approach does not work in case of ASP Button or ImageButton. If you see the page HTML source, you will be surprised that no additional hidden variable or inbuilt __doPostBack function is rendered (this will be the case if your page has only Buttons/ImageButtons but no other control having autopostback property).
The reason is that ASP.NET button or ImageButtons are rendered as default html "SUBMIT" button for which you don't need any additional logic of posting. Because of which Request.Item("__EVENTTARGET") will get you nothing. In this case you will explore that button/imagebutton id value is posted in form which you can retrieve by iterating request.

so your final code would be something like this

Function GetControlIdWhichTriggeredPost() As String
Dim ctrlId As String = Request.Item("__EVENTTARGET")
If String.IsNullOrEmpty(ctrlId) Then
For Each strId As String In Request.Form
Dim oCtrl As Control = Page.FindControl(strId)
If Not IsNothing(oCtrl) AndAlso oCtrl.GetType.Name = "Button" Then
Return strId
End If
Next
End If
Return ctrlId
End Function