简体   繁体   English

从代码后面添加JavaScript引用(C#)

[英]Add JavaScript reference from code behind (C#)

Is it possible to add javascript reference dynamically from code behind aspx.cs? 是否可以从aspx.cs后面的代码动态添加javascript引用?

Like this: 像这样:

private void AddScriptReference(string path)
{
   //Add reference to <head></head>
}

Should result in a script reference being added to the head of the page, like this: 应该导致脚本引用添加到页面的头部,如下所示:

<html>
   <head>
      <script type="text/javascript" src="path-to-script.js"></script>
   </head>
</html>

Is this possible? 这可能吗?

Bit late but thought I'd post an answer to this in case anybody else needs it. 有点迟,但我想在没有其他人需要的情况下给我发一个答案。 This solution negates the need for a ScriptManager. 此解决方案无需使用ScriptManager。

Basically, it's just a case of creating a control and then adding to the head. 基本上,它只是创建一个控件然后添加到头部的情况。 Here's the code. 这是代码。

LiteralControl javascriptRef = new LiteralControl("<script type='text/javascript' src='path_to_script.js'></script>");

Page.Header.Controls.Add(javascriptRef);

For those who want to know the syntax, here it is: 对于那些想要了解语法的人来说,这里是:

Master Page: 母版页:

<asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server"></asp:ScriptManager>

Code behind: 代码背后:

ScriptReference sr = new ScriptReference("path-to-js.js");
ScriptManager sm = (ScriptManager)this.Master.FindControl("ScriptManager");
sm.Scripts.Add(sr);

Or: 要么:

ScriptManager.RegisterClientScriptInclude(this.Page, GetType(), "UniqueID", "path-to-js.js");

But none of these solutions actually add the script to the head of the page.. 但是这些解决方案都没有将脚本添加到页面的头部。

You can use the ASP.NET Ajax ScriptManager to do so. 您可以使用ASP.NET Ajax ScriptManager来执行此操作。

Add it to your masterpage, and use ScriptManager.RegisterClientScriptInclude from your codebehind. 将其添加到您的母版页,并使用您的代码隐藏中的ScriptManager.RegisterClientScriptInclude

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM