Tuesday, July 14, 2009

Missing __doPostBack Method On ASP.NET Page

Sometimes, ASP.NET programming has called for a JavaScript call to .NET's JavaScript function __doPostBack. This function exists on (almost) every .aspx page with controls that would create a postback. Once in a while, however, you won't have a control that creates a postback (or for some other odd reason) and the __doPostBack function won't be available. In these situations, you can create your own custom method.
  1. Add two hidden fields to hold the postback information. You can add these anywhere on the page.

    <asp:HiddenField ID="__EVENTTARGET2" runat="server" />
    <asp:HiddenField ID="__EVENTARGUMENT2" runat="server" />

  2. Create a custom JavaScript __doPostBack method. I often call it __doPostBack2 just incase for some reason the original is created. Don't want to confuse the application. form1 is the form name. It might be ASPForm or something. Best way to find out is to view the source of the page and use that.

    function __doPostBack2(target,argument)
    var f = document.getElementById('form1');
    document.getElementById('__EVENTTARGET2').value = target;
    document.getElementById('__EVENTARGUMENT2').value = argument;

  3. Add the postback function to the element in question.

    <input id="txt1" type="text" ondblclick="javascript:__doPostBack2(this.id,this.value);" />
Next up: Adding custom events to controls.

No comments: