all groups > asp.net webcontrols > february 2008 >
You're in the

asp.net webcontrols

group:

Emitting Client Script


Emitting Client Script Ed Courtenay
2/15/2008 3:23:34 PM
asp.net webcontrols:
I've got a very simple custom control that requires a small section of
JavaScript to function at the client - nothing out of the ordinary.

In the overridden RenderContents method of my custom control I check
whether the required client script block has been registered with
Page.ClientScript.IsClientScriptBlockRegistered() and if not, register
it with Page.ClientScript.RegisterClientScriptBlock()

If I place the custom control on a web form, the script gets injected
into the page as expected and works as it should.

If, however, the control is placed onto a Master page the script doesn't
get injected and therefore the control fails to work; why is this
behaving differently when the control is placed on a Master page, and
Re: Emitting Client Script David R. Longnecker
2/19/2008 9:50:32 PM
Ed-

Does your MasterPage have a <form> tag set on it? If your master page is
missing <form> tags, the JavaScript doesn't seem to execute.

If you debug, you'll notice that the ClientScript._clientScriptBlocks DOES
contain your newly added code, but it isn't rendered to the HTML (try it
with and without the <form> tag and look at your generated HTML.

Here's a quick example I wrote to test this (to make sure):

Code behind:

public partial class ClientScriptBlock : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsClientScriptBlockRegistered("Test"))
{
string script = "function testScript() { alert('Hello, World!');
} testScript();";
Page.ClientScript.RegisterClientScriptBlock(GetType(), "Test",
script, true);
}
}
}

ClientScriptBlock.Master (just the body, the rest is not relevant):

<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />
</div>
</form>
</body>


Now, that works, and the generated HTML (right-click, View Source) looks
like:

<body>
<form name="aspnetForm" method="post" action="ClientScriptBlockContentPage.aspx"
id="aspnetForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1MmRk1iIo7WU1ovg+xTQd3nGBGP1wuQY="
/>
</div>


<script type="text/javascript">
//<![CDATA[
function testScript() { alert('Hello, World!'); } testScript();//]]>
</script>

<div>


</div>
</form>
</body>

Without the <form> tag, we just get:

<body>
<div>


</div>
</body>


From what I got out of the MSDN article (http://msdn2.microsoft.com/en-us/library/3hc29e2a.aspx),
the <form> tag is used to keep everything in scope for the page, though I'm
not sure why it couldn't go as a script block in the header.

Hope this helps!

-dl

--
David R. Longnecker
http://blog.tiredstudent.com

[quoted text, click to view]

AddThis Social Bookmark Button