views:

249

answers:

2

I have some code on a User Control that looks like this:

<asp:PlaceHolder id="ph1" runat="server">
    <script type="text/javascript">
        jQuery(function() {
            doSomethingAwesome();
        });
    </script>
</asp:PlaceHolder>

I want to get the contents of the PlaceHolder control. I'm trying to get it in the OnPreRender of the page this control is on. I would have expected that the contents of the PlaceHolder would be be a single Literal control, but the Controls collection is empty.

How can I get the contents of the PlaceHolder control on the server side?

+1  A: 

Literal content doesn't exist on the server because it's not in a server control.

If you need to make the script visible on the server, you'll need to explicitly put it inside a server control with the "runat=server" property set.

womp
From what I've read, I think you are right. If I wrap the <script /> tags in another control like a PlaceHolder or a Literal, I can get at them. I'm still hoping for a slightly less verbose solution.
EliThompson
Is your script dynamic? If it's a static script, then you should think about making it into a string resource and using ClientScript.RegisterScriptBlock() to add it to your page.
womp
Yes, the script is dynamic. What I have done is made a server control that inherits from PlaceHolder. It registers itself with the page it's on. You then put some JS into it. On PreRender, the page takes all the registered controls and moves their contents to the bottom of the page into another PlaceHolder. This control is for dynamic scripts, only. I do use the RegisterScriptBlock for static scripts. This may be more complexity than I want, though. I might just re-write the JS so that it doesn't need the dynamic content.
EliThompson
A: 

To get contents on client side you can do

$('#ph1').html()

If using naming containers which is likely because of user controls

$('#<%=ph1.ClientID%>').html()
Ryu
PlaceHolder controls don't actually render anything of their own to the page so #ph1 wouldn't exist. If I changed the PlaceHolder to a Panel, then your suggestion would definitely work to get the contents of the Panel (which renders to a div) on the client side.
EliThompson