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) + @"','');
 

 

posted @ Friday, November 04, 2005 2:25 PM

Print

Comments on this entry:

# Good article!

Left by Evagoras Charalambous at 11/4/2005 4:01 PM
Gravatar
I wasn't aware of this difference. Good catch and great of you to post your solution here for us!

# re: Calling __doPostBack in javascript

Left by Jørn Schou-Rode at 5/29/2006 9:57 PM
Gravatar
Great tip! Very handy when you need to implement a page with an automatically starting file download. Emit the output of the following method call using Page.ClientScript.RegisterStartupScript() and you are rolling: string.Format("setTimeout(\"{0}\",100);", Page.GetPostBackClientEvent(lbtStartDownload, null))

# re: Calling __doPostBack in javascript

Left by Welcome at 2/24/2007 5:56 PM
Gravatar

not working

("setTimeout(\"{0} Very handy when you need to implement a page with an automatically starting file download. Emit the output of the following method call using Page.ClientScript.RegisterStartupScript() and you are rolling: string.Format("setTimeout(\"{0}

# re: Calling __doPostBack in javascript

Left by Bhupinder at 10/21/2007 11:48 PM
Gravatar
have a nice day

# re: Calling __doPostBack in javascript

Left by Oleh at 11/16/2007 6:51 PM
Gravatar
Instead of __doPostBack('" + UniqueIDWithDollars(ctrl) + @"','');
use
__doPostBack('" + ctrl.ClientID + @"',''); //for IE
but for other browsers you should use
__doPostBack('" + ctrl.UniqueID + @"','');

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 11/16/2007 11:04 PM
Gravatar
Oleg,
I beleive, that Page.GetPostBackEventReference will handle different browsers for you.
Also see AJAX client library. It should have similar methods.

# re: Calling __doPostBack in javascript

Left by Rajni Padhiyar at 11/29/2007 4:17 AM
Gravatar
You can do post back using hidden input's click event by javascript.

Thanks
Regards
Rajni Padhiyar
Project Leader
Rajni Padhiyar

# re: Calling __doPostBack in javascript

Left by praveen at 1/27/2008 9:46 PM
Gravatar
Using __doPostBack with ASCX page

Ascx page

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Test.ascx.cs" Inherits="Test" %>
<script language=javascript>
function call_me()
{
__doPostBack('frmTest$btnHdn',""); (need to find the Unique ID of the hidden button first and assign that id here)
}
function __doPostBack(eventTarget, eventArgument)
{
var theform;
if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
{
theform = document.forms["frmDef"];
}
else
{
theform = document.frmDef; (frmDef is the form id of aspx page to this control is registered – check below the ascx form id)
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
</script>
<input type=button runat=server onclick="call_me();" id="btnClick" />
<input type=button runat=server id="btnHdn" visible=false onserverclick="Call_Server"/>

Code behind

protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterHiddenField("__EVENTTARGET", this.btnHdn.ClientID); (need to register these two events on pageload)
Page.RegisterHiddenField("__EVENTARGUMENT","");
}

protected void Call_Server(Object sender, EventArgs e)
{
Response.Write("Called from JS");
}

# re: Calling __doPostBack in javascript

Left by kiquenet at 2/13/2008 2:40 AM
Gravatar
Hi mister,
where is the code about JsScriptHelper ?

thanks.

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 2/13/2008 8:54 AM
Gravatar
In My JScriptHelper class http://geekswithblogs.net/mnf/articles/102574.aspx

# re: Calling __doPostBack in javascript

Left by rajesh at 6/16/2008 8:08 PM
Gravatar
hi
i have used button click for hidding datagrid
but when we click refresh it is again showin
how to make autopostback false in javascript

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 6/29/2008 10:46 PM
Gravatar
rajesh,
click refresh -is the same as open the page again.
If you want to keep state (e.g is datagrid visible)after Refresh, you probably need to use Session.

# re: Calling __doPostBack in javascript

Left by Golam Kibria at 12/21/2008 5:25 PM
Gravatar
Why do use second parameter in __dopostback()

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 12/27/2008 12:52 AM
Gravatar
Golam Kibria,
The second parameter eventArgument contains any additional data associated with the control.
See
Understanding the JavaScript __doPostBack Function

# re: Calling __doPostBack in javascript

Left by Eva M. Higueras at 1/27/2009 9:19 PM
Gravatar
Great tip! You can see aditional information (in Spanish) here: Provocar un PostBack desde javascript con ASP.NET

Thanks.

# re: Calling __doPostBack in javascript

Left by Nellaikumar at 7/23/2009 7:35 AM
Gravatar
Thanks, providing nice article..It helped lot.

# re: Calling __doPostBack in javascript

Left by .Net Training Classes at 9/4/2009 12:29 AM
Gravatar
This code is really helpful to me...
Thanks

.Net Training Classes
Sharma Web Academy

Contact Us at
www.sharmawebacademy.com
Mail Us at
harish.solanki@sharmainfoway.com

# .Net Programming Training

Left by Shaishavi Sen at 9/11/2009 10:39 AM
Gravatar
Thanks a lot for sharing code it would be helpful to all student and programmer and one more thing

We provide live projects with complete technical training for students studying in MCA, BCA, BE, PGDCA, MSc IT and other computer career oriented students providing them with Live International Projects
Contact us
info@dslacademy.com
http://www.dslacademy.com

# re: Calling __doPostBack in javascript

Left by Harald at 11/4/2009 6:18 AM
Gravatar
Just call

__doPostBack('<%= yourControl.UniqueID %>', '');

Then, you have everything you want.

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 11/5/2009 4:52 AM
Gravatar
Harald,
UniqueID can have ':' inside, that should be replaced with '$'.
<%=Page.GetPostBackEventReference(yourControl)%> utilize ASP.NET Framework and should be safe.

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345