ASP.NET:如何(以编程方式)附加

场景如下:

我正在开发一个新的 ASP.NET 应用程序,该应用程序中几乎所有网页都使用母版页,其中一些网页嵌套到 4 层。由于项目的规模,我被迫将网页组织到不同深度级别的文件夹中。位于根目录的全局主页面(大写)包含一些有用的 Javascript 函数,这些函数在整个 Web 应用程序中都使用,我想将这些函数放在一个 .js 文件中,以便保留这些函数,好吧,按顺序:D。 (它们当前嵌入到母版页中)。

然而,我最近发现

因此,本质上,考虑到这种情况,我想问您,通过代码插入

或者这不是正确的方法,我应该完全使用其他方法?

This is the scenario:

I'm working on a new ASP.NET application that uses master pages for virtually all of the web pages in it, a few of them nested to 4 levels. Due to the size of the project, I was forced to organize the web pages into folders, at various depth levels. The global, Master (in uppercase) page, located at the root directory, contains some useful Javascript functions that are used all along the web app, and I wanted to place these functions together in a single .js file, in order to keep things, well, in order :D . (They're currently embedded into the Master page).

I discovered recently, however, that <script> tags placed on the <head> block can't have their paths specified as, for example, "~/Scripts/Utils.js", since ASP.NET does not seem to recognize these paths on <script> tags (yet, strangely enough, it does recognize them on <link> tags). I'm trying to avoid inserting a <script> tag on every single web page on the site specifying a relative path to the .js file (that's sort of why I wanted to use master pages in the first place).

So, in essence, given this scenario, I want to ask you, what's the recommended way of inserting, via code, <script> tags into the <head> block of a web page so that I can use, when specifying the link to the .js file, something like        Something.Something(Something, Page.ResolveURL("~/Scripts/Utils.js"));        in the global Master page, so it will resolve to the right path on all the web pages of the application, no matter what directory are they inside?

Or is this not the right approach, and I should be using something else entirely?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩世 2024-12-02 09:21:06

您可以使用ClientScriptManager

Page.ClientScript.RegisterClientScriptInclude("MyScript", ResolveUrl("~/Scripts/MyScript.js"));

第一个参数是代表脚本文件的唯一键,这是为了阻止后续脚本使用相同的键注册。例如,您可能有一些执行相同操作并且可以执行多次的共享代码,因此通过指定一个键,您可以确保脚本仅注册一次。

You can use the ClientScriptManager:

Page.ClientScript.RegisterClientScriptInclude("MyScript", ResolveUrl("~/Scripts/MyScript.js"));

The first argument is a unique key representing the script file, this is to stop subsequent scripts being registered with the same key. E.g. you may have some shared code that does the same thing and could be executed multiple times, so by specifying a key, you ensure the script is only registered the once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文