【问题标题】:How to add correctly a script to a control?如何正确地将脚本添加到控件?
【发布时间】:2016-12-17 06:56:33
【问题描述】:

我有这个代码:

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。 msdn.microsoft.com/en-us/library/…
  • 我将很快测试。您能解释一下为什么问题中显示的代码结果是 HTML-encoded 吗?
  • InnerText 对文本进行编码。 InnerHtml 应该允许它通过未编码。
  • @BertEvans,我在写问题之前也用 InnerHtml 进行了测试,我遇到了同样的行为。

标签: javascript asp.net vb.net asp.net-controls


【解决方案1】:

根据您的需要,您可能希望通过多种方式来解决此问题。

对于您始终希望可用于您的控件的少量脚本,您最常作为字符串嵌入代码中,您将需要使用RegisterClientScriptBlockRegisterStartupScript。您选择哪一个主要取决于您希望在哪里呈现脚本。您可以找到一个很好的解释,说明何时选择一个或另一个 here

您可能想要选择的另一个选项是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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多