views:

570

answers:

4

After trying to understand why client code is not rendered in a page (injected by user control) I found this link, it turns out you must have a form tag for it to work (Page.RegisterClientScriptBlock did declare this but ClientScriptManager.RegisterClientScriptBlock which I use does not say anything regarding this).
I am using Visual studio 2005.
Does anyone know if this has been solved?

Edit:
To clarify, I want my control to add javascript code to the head section of the page without having to use the

<form runat="server"

I have tried adding it using:

HtmlGenericControl x = new HtmlGenericControl("script");
x.InnerText = "alert('123');";
Page.Header.Controls.Add(x);

But this did not work for me.

+2  A: 

As far as I know this functions the same in current versions, you can test it very simply though.

Update

per discussion in the comments, the only "workaround" that I could think of would be for your to manually insert the script into the "head" section of the page on your own, using a runat="server" declaration on the Head element.

Mitchel Sellers
I did test it and it does not work without the form tag. is there any work-around so I don't have to use the form runat='server' ?
Dror
Edited answer with a bit of detail.
Mitchel Sellers
A: 

The MSDN Page for registerclientscriptblock here says:

The client-side script is emitted just after the opening tag of the Page object's <form runat= server> element. The script block is emitted as the object that renders the output is defined, so you must include both tags of the <script> element.

If you do not want to include a form, than you will basically need to build your own implementation of it.

epascarello
What do you mean by "build your own implementation of it" - I have no use for the form itself, I just want the script to be added to the page.
Dror
A: 

Got it!
My mistake was not doing it in the OnPreRender method (I used the Render method).

Now all that is needed is - like Mitchel Sellers wrote, set the header to runat server and than add to it's controls:

 HtmlGenericControl x = new HtmlGenericControl("script");
 x.InnerText = GetScriptSection();
 Page.Header.Controls.Add(x);

Thanks for pointing me to the right direction!

Dror
A: 

Minor clarification for anyone seeing this:

The form tag must have the runat="server" attribute set, e.g.

<form id="theform" runat="server">

Just placing a regular HTML form tag in the page will not help.