Search
Close this search box.

Calling __doPostBack in javascript

Update: There is an existing .Net Framework method Page.GetPostBackEventReference that emits client-side script that initiates postback and also provides a reference to the control that initiated the postback event. It is well described in MSDN article “Generating Client-Side Script for Postback“. So my function should call and  in most cases GetPostBackEventReference can be used directly.

Original Post:

I’ve used a function to submit postback from my javascript by passing Id of the link server control as it was suggested in article “How postback works in ASP.NET” 

   //call the postback function with the right ID
 __doPostBack(‘ControlId’,”);
and it worked fine for a while.

However when I moved the link to the User control, it stopped to work.

I recognized that I need to provide fully qualified Control.ClientId but it didn’t work.
In debugger I found that when calling the __doPostBack(), ASP.NET generates ID with dollar – $ -separator, not underscore that is used in ClientID, e.g. ‘userContol1$linkContol1’.

I found confirmation to this in ASP.NET Server Control – Design Time Support  and .NET Development: PressButton Design and Server Control . Microsoft provides  UniqueIDWithDollars  internal method, that can be accessed through reflection.

However I found that it is simpler just to duplicate code in static function.

The working version of javascript function to __doPostBack :

public static bool RegisterFunctionToPostBack(string sFunctionName,
                                              Control ctrl)

{  // from http://www.xefteri.com/articles/show.cfm?id=18 How postback works in
   // ASP.NET

  if (HttpContext.Current.Request.Browser.JavaScript)

  {
    string sJS = "    function " + sFunctionName +
                 @"()

                        {

                            //call the postback function with the right ID

                             __doPostBack('" +
                 UniqueIDWithDollars(ctrl) +
                 @"','');

                        }";

    sJS = JScriptHelper.JScript(sJS);

    ctrl.Page.RegisterStartupScript(sFunctionName, sJS);

    return true;
  }

  return false;
}

// from http://www.codeproject.com/aspnet/DesignTimeSupport.asp

public static string UniqueIDWithDollars(Control ctrl)

{
  string sId = ctrl.UniqueID;

  if (sId == null)

  {
    return null;
  }

  if (sId.IndexOf(':') >= 0)

  {
    return sId.Replace(':', '$');
  }

  return sId;
}

If I would start the function from the scratch, I probably would consider ScriptCallback/AJAX approach.

ctrl.Page.GetPostBackEventReference(ctrl)  instead of 
__doPostBack(‘” + UniqueIDWithDollars(ctrl) + @”‘,”); 

This article is part of the GWB Archives. Original Author: Michael Freidgeim

Related Posts