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

How to add correctly a script to a control?

本文关键字:添加 控件 脚本 正确地      更新时间:2023-09-26

我有这样的代码:

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或RegisterStartupScript。你选择哪一个主要取决于你想在哪里渲染脚本。你可以在这里找到一个很好的解释,什么时候选择一个或另一个。

您可能想要选择的另一个选项是RegisterClientScriptResource。当我编写一个包含大量JavaScript的服务器控件或者我想将其作为类库的一部分时,我发现这个选项最有用。使用此选项,您可以将脚本作为嵌入式资源编译到库中,然后将库包含在其他项目中。当我拥有的不仅仅是几行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)