I'm trying to manually call the ASP.NET (3.5) javascript postback function __doPostBack
from my javascript code. The problem is that the postback script block, that is normally rendered right after the beginning of the <form>
tag (and the hidden fields), is occasionally rendered near the closing </form>
tag.
Is there any way to force it to be rendered near the beginning of the form tag? Also, how does ASP.NET decide when/where to render the postback client script block?
Edit > Additional Info:
The javascript code resides inside a user control that references the __doPostBack
function. The control itself does not contain any 'postback controls' that would call that function. (When I mention 'postback controls', I mean ASP.net controls that call the __doPostBack
function and not the asp.net ImageButton
and Button
controls)
Based on what I've observed and @Brian's comment on the dependency of the postback script on the availability of 'postback controls' on the page, I've found that when the page contains controls that cause postback, the __doPostBack script block is rendered after the opening <form>
tag and when there are none, it renders them near the closing </form>
tag (or according to this it's not even supposed to be rendered). Now it would make sense for ASP.NET not to render the postback script if there are no controls that require it, but the apparent position of the script near the closing tag is the one that still eludes me. I haven't been able to find any documentation that suggests this behavior. All I've been able to find was this.
Having said that, I've found a couple ways around this issue:
- Add a 'postback control' and set its visibility to hidden via css (not the Visible property). eg.
<asp:LinkButton ID="RequirePostBackScriptLink" runat="server" style="display:none;" />
(this is what I'm using) - Add the control to the
Page.RegisterRequiresPostBack
and implement theIPostBackDataHandler
interface.
Finally, as @Jonathan_Bates mentioned in his post, the proper thing to do is to wrap the reference to __doPostBack
inside a function that is an event handler to load
(or ready
if you're using jquery). That way, there wouldn't be a need to depend on the actual placement of the __doPostBack
script.
It'd be great if anyone can provide more info on this, aforementioned, behavior.