Geeks With Blogs

Michael Freidgeim's Blog MS .Net Development

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 on Friday, November 4, 2005 2:25 PM ASP.NET , CSS/DHTML/JavaScript | Back to top


Comments on this post: Calling __doPostBack in javascript

# Good article!
Requesting Gravatar...
I wasn't aware of this difference. Good catch and great of you to post your solution here for us!
Left by Evagoras Charalambous on Nov 04, 2005 4:01 PM

# re: Calling __doPostBack in javascript
Requesting 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))
Left by Jørn Schou-Rode on May 29, 2006 9:57 PM

# re: Calling __doPostBack in javascript
Requesting 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}
Left by Welcome on Feb 24, 2007 5:56 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
have a nice day
Left by Bhupinder on Oct 21, 2007 11:48 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Instead of __doPostBack('" + UniqueIDWithDollars(ctrl) + @"','');
use
__doPostBack('" + ctrl.ClientID + @"',''); //for IE
but for other browsers you should use
__doPostBack('" + ctrl.UniqueID + @"','');
Left by Oleh on Nov 16, 2007 6:51 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Oleg,
I beleive, that Page.GetPostBackEventReference will handle different browsers for you.
Also see AJAX client library. It should have similar methods.
Left by Michael Freidgeim on Nov 16, 2007 11:04 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
You can do post back using hidden input's click event by javascript.

Thanks
Regards
Rajni Padhiyar
Project Leader
Rajni Padhiyar
Left by Rajni Padhiyar on Nov 29, 2007 4:17 AM

# re: Calling __doPostBack in javascript
Requesting 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");
}
Left by praveen on Jan 27, 2008 9:46 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Hi mister,
where is the code about JsScriptHelper ?

thanks.
Left by kiquenet on Feb 13, 2008 2:40 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
In My JScriptHelper class http://geekswithblogs.net/mnf/articles/102574.aspx
Left by Michael Freidgeim on Feb 13, 2008 8:54 AM

# re: Calling __doPostBack in javascript
Requesting 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
Left by rajesh on Jun 16, 2008 8:08 PM

# re: Calling __doPostBack in javascript
Requesting 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.
Left by Michael Freidgeim on Jun 29, 2008 10:46 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Why do use second parameter in __dopostback()
Left by Golam Kibria on Dec 21, 2008 5:25 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Golam Kibria,
The second parameter eventArgument contains any additional data associated with the control.
See
Understanding the JavaScript __doPostBack Function
Left by Michael Freidgeim on Dec 27, 2008 12:52 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Great tip! You can see aditional information (in Spanish) here: Provocar un PostBack desde javascript con ASP.NET

Thanks.
Left by Eva M. Higueras on Jan 27, 2009 9:19 PM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Thanks, providing nice article..It helped lot.
Left by Nellaikumar on Jul 23, 2009 7:35 AM

# re: Calling __doPostBack in javascript
Requesting 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

Left by .Net Training Classes on Sep 04, 2009 12:29 AM

# .Net Programming Training
Requesting 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
Left by Shaishavi Sen on Sep 11, 2009 10:39 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Just call

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

Then, you have everything you want.
Left by Harald on Nov 04, 2009 6:18 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Harald,
UniqueID can have ':' inside, that should be replaced with '$'.
<%=Page.GetPostBackEventReference(yourControl)%> utilize ASP.NET Framework and should be safe.
Left by Michael Freidgeim on Nov 05, 2009 4:52 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Thanks it works !!!!!
Left by kiran on Dec 24, 2009 11:17 AM

# Calling __doPostBack in javascript
Requesting Gravatar...
good, its nice code.
Left by ewitttas on Jan 20, 2010 2:56 AM

# Calling javascript function before page render
Requesting Gravatar...
Please tell me that i want to call javascipt function just before the page is rendered completly .. that function should be last funtion
Left by sanam on Jul 15, 2010 5:19 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Thanks, exactly what I needed.
Left by Janusz Stabik on Jan 07, 2011 4:18 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
This code is really helpful to me...it works !!!!!
Left by torrent download on Jan 31, 2011 7:04 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Page.GetPostBackEventReference will handle different browsers for you, i think!!
Left by Adrianna Deville on Feb 23, 2011 1:09 PM

# re: Calling __doPostBack in javascript
Requesting 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
Left by Roman on Mar 12, 2011 1:08 PM

# re: Calling __doPostBack in javascript
Requesting 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
Left by Marimuthu on Feb 04, 2012 12:47 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
Hi Marimuthu,
Consider to use AJAX calls, e.g. JQueryUI controls
Left by Michael Freidgeim on Feb 05, 2012 11:29 AM

# re: Calling __doPostBack in javascript
Requesting Gravatar...
it is not working in IE

it is giveing error that __EVENTTARGET is null or not an object
Left by akshay on Aug 12, 2013 7:48 PM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net | Join free