如何将脚本正确添加到控件?

How to add correctly a script to a control?

我有这个代码:

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)

这会生成以下内容:

<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>

问题在于它是 HTML 编码的。我的问题是:如何确保脚本不会被 HTML 编码?

根据您的需要,您可能想通过多种方式来解决这个问题。

对于您始终希望可用于控制的少量脚本,您最常将其作为字符串嵌入代码中,您将需要使用 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

您可能要选择的另一个选项是 RegisterClientScriptResource。当我编写具有大量 JavaScript 的服务器控件或我想将其作为 class 库的一部分包含时,我发现此选项最有用。使用此选项,您可以将脚本作为嵌入式资源编译到库中,然后将库包含在其他项目中。当我有不止几行 JavaScript.

时,编辑体验会好很多

对于这种特殊情况:

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)