Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a javascript function before postback of asp.net button?

I'm using Javascript to create a DIV element and open up a new page by using onclientclick. This works great. Now, I need to write to it from the server side and this element must be created before it is posted back.

How do I get the javascript to execute before the postback?

Currently, I have to press the button twice because the element doesn't exist to write too on the first click.

To be clear, I need this to execute before the "OnClick" of the button.

Update: It looks like the Javascript function is called before the postback but the element is not updated until I run the second postback. Hmm

Update: Unfortunately it is a bit more complicated then this.

I'm creating a div tag in javascript to open a new window. Inside the div tag, I'm using a databinding syntax <%=Preview%> so that I can get access to this element on the server side. From the server side, I'm injecting the code.

I'm thinking this may be a chicken-egg problem but not sure.

UPDATE!

It is not the Javascript not running first. It is the databinding mechanism which is reading the blank variable before I'm able to set it.

Hmm

like image 621
Curtis White Avatar asked May 27 '10 16:05

Curtis White


People also ask

How do you PostBack in JavaScript?

How to Raise a Postback from JavaScript? To do this, we need to just call the __doPostBack() function from our javascript code. When the above function is called, it will raise a postback to server.

How do I stop PostBack?

The postback on submit button can be avoided by giving return=false in the event handler function as below.

Does ASP NET do PostBack?

PostBack is the name given to the process of submitting an ASP.NET page to the server for processing. PostBack is done if certain credentials of the page are to be checked against some sources (such as verification of username and password using database).


1 Answers

you don't have to rely on server controls to perform postbacks in asp.net. you can gain finer control of your app by posting from javascript whenever you are ready..

the framework auto generates a function called __doPostback(.....) and eventually calls it every time it needs to do a postback.

so. instead of using server control button, you can have a regular <button onclick="foo()" /> than once you're done performing all that you need, just call the __doPostback function.

asp.net gives you a nifty way to access that function with Page.GetPostbackClientEvent (i believe, but there are couple methods that support this methodology) http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx

like image 98
Sonic Soul Avatar answered Oct 19 '22 07:10

Sonic Soul