Lajos Arpad Lajos Arpad - 3 months ago 7
Vb.net Question

How to add correctly a script to a control?

I have this code:

Dim script = New HtmlGenericControl("script")
script.Attributes.Add("type", "text/javascript")
script.InnerText = "var alohaInterval = setInterval(function() {if (typeof Aloha === ""undefined"") {return;} clearInterval(alohaInterval); Aloha.ready(function() {Aloha.jQuery("".editable-content"").aloha();})}, 100);"
htmlControl.Controls.Add(script)


This generates the following thing:

<script type="text/javascript">var alohaInterval = setInterval(function() {if (typeof Aloha === &quot;undefined&quot;) {return;} clearInterval(alohaInterval); Aloha.ready(function() {Aloha.jQuery(&quot;.editable-content&quot;).aloha();})}, 100);</script>


The problem is that it is HTML-encoded. My question is: how to make sure that the script will not be HTML-encoded?

Answer

There are several ways you may want to go about this depending on what you need.

For a small amount of script that you always want available for your control, that you are most commonly embedding in the code as a string, you will want to use RegisterClientScriptBlock or RegisterStartupScript. Which one you choose depends mainly on where you want the script to be rendered. You can find a good explanation for when to choose one or the other here.

Another option you may want to choose is RegisterClientScriptResource. I find this option most useful when I am writing a server control that has a significant amount of JavaScript or that I want to include as a part of a class library. Using this option you can compile the script into the library as an embedded resource and then include the library in other projects. The editing experience is just that much better when I have more than just a couple lines of JavaScript.

For this particular case:

ClientScript.RegisterClientScriptBlock(Me.GetType, "alohainit", "var alohaInterval = setInterval(function() {if (typeof Aloha === ""undefined"") {return;} clearInterval(alohaInterval); Aloha.ready(function() {Aloha.jQuery("".editable-content"").aloha();})}, 100);", True)