简体   繁体   English

将外部javascript文件视为Aspx Page的一部分

[英]Treat external javascript file as part of Aspx Page

I know you can't use asp net server tags in an external javascript file. 我知道你不能在外部javascript文件中使用asp net server标签。 This is a bit of pain, because it forces you to declare your variables that need ClientID in the aspx page and then you refer to them in the external javascript file. 这有点痛苦,因为它会强制您在aspx页面中声明需要ClientID的变量,然后在外部javascript文件中引用它们。 Not very clean. 不是很干净。 Currently I use script manager's composite script to register my scripts... It would be nice if I could have the script injected and the server tags processed as if it was part of the page. 目前我使用脚本管理器的复合脚本来注册我的脚本...如果我可以注入脚本并处理服务器标签就好像它是页面的一部分那样会很好。 Is this possible? 这可能吗?

I know there is RegisterClientScript but this doesn't seem to honor the script tags either. 我知道有RegisterClientScript,但这似乎也不尊重脚本标签。 I'm wondering if there is a solution someone has come up with to just pull the contents of the javascript file and shove them into the aspx page before it's processed so that the server tags can be processed. 我想知道是否有人提出解决方案只是拉出javascript文件的内容并在处理之前将它们推入aspx页面,以便可以处理服务器标签。 I've looked all over the web and don't see any good solution to this beyond using the server tags in the aspx page or generating the ids of controls, etc. server side and generating script. 我已经浏览了整个网络,除了在aspx页面中使用服务器标签或生成控件ID等服务器端和生成脚本之外,没有看到任何好的解决方案。

I know you can't use asp net server tags in an external javascript file 我知道你不能在外部javascript文件中使用asp net server标签

You can create an ASPX page to generate dynamic javascript 您可以创建一个ASPX页面来生成动态JavaScript

<%@ Page Language="C#" AutoEventWireup="false"
CodeFile="script.aspx.cs" Inherits="scripts_script"
EnableViewState="false" StyleSheetTheme="" %>
function test() {
    testinfo.innerHTML = "<%= MyVariable %>";
}

Make sure to set StyleSheetTheme="" otherwise the runtime will insert a <head> which you don't want 确保设置StyleSheetTheme=""否则运行时将插入您不想要的<head>

And in the code behind set the ContentType to application/x-javascript 并在后面的代码中将ContentType设置为application/x-javascript

using System;

public partial class scripts_script
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.Response.ContentType = "application/x-javascript";
    }
}

Now you can use this ASPX page as if it were a .js file. 现在您可以使用此ASPX页面,就像它是.js文件一样。

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

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