Thursday, September 27, 2007

RegisterOnSubmitStatement and Render

Yesterday I was trying to make one of my controls keep its scroll position. Since you can't set a scrollTop attribute (which I think it is dumb, but that's another issue) I used a HiddenField and some Javascript. Mainly one at submit that loaded the scrollTop value in the hidden field and one on load to re-set it.

Since the logic of my control was mainly in the Render method of the control, I wrote the RegisterStartupScriptBlock and RegisterOnSubmitStatement lines there. It worked like a charm, but then I decided to see if it works WITHOUT Ajax.Net by removing the update panel I have been using. It failed!

I wasted like two hours before I understood that the RegisterOnSubmitStatement did not add anything to the page. I moved it in the OnPreRender method of the control and it worked!

So, long story short: DO NOT use RegisterOnSubmitStatement in the Render method of controls, as I believe the onsubmit (and possibly ClientScriptBlocks) are rendered by the page before any of the controls on it.

Someone else talks about it here.