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 4, 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.

# re: Calling __doPostBack in javascript

Left by kiran at 12/24/2009 11:17 AM
Gravatar
Thanks it works !!!!!

# Calling __doPostBack in javascript

Left by ewitttas at 1/20/2010 2:56 AM
Gravatar
good, its nice code.

# Calling javascript function before page render

Left by sanam at 7/15/2010 5:19 AM
Gravatar
Please tell me that i want to call javascipt function just before the page is rendered completly .. that function should be last funtion

# re: Calling __doPostBack in javascript

Left by Janusz Stabik at 1/7/2011 4:18 AM
Gravatar
Thanks, exactly what I needed.

# re: Calling __doPostBack in javascript

Left by torrent download at 1/31/2011 7:04 AM
Gravatar
This code is really helpful to me...it works !!!!!

# re: Calling __doPostBack in javascript

Left by Adrianna Deville at 2/23/2011 1:09 PM
Gravatar
Page.GetPostBackEventReference will handle different browsers for you, i think!!

# re: Calling __doPostBack in javascript

Left by Roman at 3/12/2011 1:08 PM
Gravatar
Hi,

I do not understand why go such a hard way, because there is a simple solution, just used element.UniqueID in any cases.
This will give the correct ID, from inside the MasterPage or ascx control.

See more details on http://extremedev.blogspot.com/2011/03/aspnet-dopostback-not-working.html

# re: Calling __doPostBack in javascript

Left by Marimuthu at 2/4/2012 12:47 AM
Gravatar
hi,
i am using asp.net 1.1, i need ur help, when i am selecting a dropdown list the whole page will be reloaded, how to avoid this, please do the need full.
thanks & regards,
Marimuthu

# re: Calling __doPostBack in javascript

Left by Michael Freidgeim at 2/5/2012 11:29 AM
Gravatar
Hi Marimuthu,
Consider to use AJAX calls, e.g. JQueryUI controls

# re: Calling __doPostBack in javascript

Left by akshay at 8/12/2013 7:48 PM
Gravatar
it is not working in IE

it is giveing error that __EVENTTARGET is null or not an object

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«August»
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456