views:

178

answers:

1

Hello. I am needing a piece of javascript to be run whenever a postback occurs. Well, actually multiple pieces. This is to be done inside a custom control, so the javascript code that should be run may be used a lot of times.

I currently have it so that the custom control will create a chain of "overrides" for the __onPostBack function. I feel this is pretty messy and it also does not handle regular post backs caused by Buttons.

tl;dr: What is the best way of executing a piece of javascript code when a postback happens? (that is, execute the code before the postback hits the server)

(Also, aiming for IE 7+ and Firefox compatibility)

+2  A: 

You could set the onSubmit event on the form:

ClientScript.RegisterOnSubmitStatement(this.GetType(), "MyScript", "alert('Hello')");

Old and new way is described here: http://weblogs.asp.net/vga/archive/2004/03/01/NoMoreHijackingOfDoPostBackInWhidbey.aspx

asgerhallas
And the new way (setting onsubmit, described last in the post) should also be compatible with the custom controls and buttons.
asgerhallas
Wow, I thought the RegisterSubmit bit didn't work for AJAX.. I guess microsoft isn't too bad after all!
Earlz